我无法让 $compile
手动使用 ng-repeat
。这里有一个类似的问题:ngRepeat in compiled by $compile does not work ,但它并没有解决这里的问题,因为我手动调用范围上的 $digest
但它仍然不起作用。
我指的代码在这里:
js:
angular.module('myApp', []);
angular.module('myApp').directive('test', ['$compile', '$rootScope', '$timeout',
function ($compile, $rootScope, $timeout) {
var myScope = $rootScope.$new();
myScope.numbers = [1, 2, 3];
var html = '<div ng-repeat="number in numbers">{{ number }}</div>';
var html2 = '<div>{{ numbers }}</div>';
var returnObject = $compile(html)(myScope);
$timeout(function () {
myScope.$digest();
console.log(returnObject);
});
return {};
}
]);
html:
<html ng-app="myApp">
<head>
...
</head>
<body>
<h1 test>Hello Plunker!</h1>
</body>
</html>
plunker 链接:http://plnkr.co/edit/RC1EILu16GPr0MGmSpcb?p=preview
如果您将 html
变量切换为 html2
,它将按预期插入并返回对象。但在目前的状态下,我希望得到一个包含 1、2、3 ...的 DIV 集合。
最佳答案
在内部,ng-repeat 通过向调用 ng-repeat 的指令的父元素添加元素来工作。您编译的 ng-repeat 没有添加其元素的父级,因此它无法工作。
添加父 div ( Plunk )
var html = '<div><div ng-repeat="number in numbers">{{ number }}</div></div>';
var html2 = '<div>{{ numbers }}</div>';
var returnObject = $compile(html)(myScope);
$timeout(function () {
myScope.$digest();
console.log(returnObject.children());
关于javascript - $compile 和 ng-repeat 没有返回正确的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28824090/