2
我正在尝试向页面中添加一个动态添加的元素指令,但它不起作用,并且在添加的页面中进行编译。这是plunker代码。代码有什么问题?无法将动态添加的指令编译到页面中
http://plnkr.co/edit/BFPxAvEahT1I930mvB5r
<!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,$compile){
$scope.xx = ['x','c','y','z','a'];
$scope.add = function(){
var templ = document.getElementById('test').innerHTML;
templ = templ+'<datan-type content="test1" con="{{xx}}"></datan-type>';
document.getElementById('test').innerHTML = templ;
//$compile(document.getElementById('test').innerHTML)($scope);
alert(document.getElementById('test').innerHTML);
}
});
app.directive('datanType', function ($compile) {
return {
restrict: 'E',
replace: true,
link: function (scope, ele, attrs) {
var testTemplate1 = '<h1 ng-repeat="x in arr">Test{{x}}</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>
<div id="test"></div>
<button ng-click="add()">Add Form Elem Eg - Error Area</button>
</body>
</html>
为什么这会有所作为?那是因为双向绑定在这里不起作用吗? – Gary
我很确定,在'angular.element'中的HTML包装会导致编译以不同的方式对待它。我对内部知识不够了解,不知道究竟是什么。如果你看网上的例子,你通常会看到这样的HTML包装,所以我只是认为这是标准的。 – KreepN
我能否在控制器中使用'this'(controllerAs)语法来获得相同代码的指令并获得ng-repeat的指令? – Gary