Я пытаюсь добавить элементы формы динамически с помощью JS и потребуется директива. Я могу добавлять элементы формы, но когда у меня есть ng-options или ng-repeat, он не компилируется. У меня есть пример директивы, которую я использую для демонстрации.
http://plnkr.co/edit/JOzTWB6tuyilCJ8Rj37Q
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller("fCtrl",function($scope){
$scope.xx = ['x','c','y','z','a'];
});
app.directive('datanType', function ($compile) {
var testTemplate1 = '<h1 ng-repeat="x in xx">Test</h1>';
var testTemplate2 = '<h1>Test2</h1>';
var testTemplate3 = '<h1>Test3</h1>';
var getTemplate = function(contentType){
var template = '';
switch(contentType){
case 'test1':
template = testTemplate1;
break;
case 'test2':
template = testTemplate2;
break;
case 'test3':
template = testTemplate3;
break;
}
return template;
};
var linker = function(scope, element, attrs){
element.html(getTemplate(attrs.content));
$compile(element.contents())(scope);
};
return {
restrict: "E",
replace: true,
link: linker,
scope: {
content:'=',
con:'@'
}
};
});
</script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-controller="fCtrl">
<p>Result:</p>
<datan-type content="test1" con="{{xx}}"></datan-type>
</body>
</html>
Попробуйте этот метод, его рабочий http://plnkr.co/edit/NTG0LBa1dIPWcGGupJgt?p=preview
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller("fCtrl",function($scope){
$scope.xx = ['x','c','y','z','a'];
});
app.directive('datanType', function ($compile) {
return {
restrict: 'E',
replace: true,
link: function (scope, ele, attrs) {
var testTemplate1 = '<h1 ng-repeat="x in arr">Test</h1>';
var testTemplate2 = '<h1>Test2</h1>';
var testTemplate3 = '<h1>Test3</h1>';
var template = '';
scope.arr = eval(attrs.con);
switch(attrs.content){
case 'test1':
template = testTemplate1;
break;
case 'test2':
template = testTemplate2;
break;
case 'test3':
template = testTemplate3;
break;
}
ele.html(template);
$compile(ele.contents())(scope);
}
};
});
</script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-controller="fCtrl">
<p>Result:</p>
<datan-type content="test1" con="{{xx}}"></datan-type>
</body>
</html>
Это должно сработать. Ниже перечислены следующие изменения:
con уже привязан к области видимости. нет необходимости использовать attrs
var testTemplate1 = '<h1 ng-repeat="x in con">Test {{x}}</h1>';
Изменено @to = для привязки свойства scope к родительской области (@bounds as string, см. Это
scope: {
content: '=',
con: '='
}
Изменено {{xx}} на xx
<datan-type content="test1" con="xx"></datan-type>
Рабочий плункер http://plnkr.co/edit/P54mZhXWE7AnjfCWbQRb
switch
используйтеng-switch
.