Angular 应用程序接收数组中的数据。有了这些数据, $compile 就被用来创建一个 Angular 指令。示例...
for(i = 0; i < trueTest.length; i++) {
var test = trueTest[i];
$scope.directiveData = {
blockId: test.blockId,
dataType: test.dataType,
type: test.type,
directiveType: test.directiveType
};
$compile("<my-directive block-id='{[{ directiveData.blockId }]}' block-data-type='{[{ directiveData.dataType }]}' block-type='{[{ directiveData.type }]}' block-directive-type='{[{ directiveData.directiveType }]}'></my-directive>")($scope.$new());
elem.find('.SomeElement').append(el);
}
自定义指令my-directive
具有独立的范围,其值blockId
、blockDataType
等...
最重要的值是 my-directive
内的 blockId
。它确定该指令中将显示什么类型的数据。问题在于,似乎 $compile
在循环结束后创建元素,因此在 $compile
创建的每个指令中,隔离范围属性始终是循环中创建的最后一个.
我的猜测是 $compile 异步创建元素(指令),因此当循环完成时,只会使用 $scope.directiveData
的当前值创建指令。或者,指令被创建为普通 DOM 元素,但作用域随后创建,从而使用 directiveData
对象的最后一个值创建所有指令的作用域。
谁能解释一下这里到底发生了什么?
编辑
这是问题的 jsFiddle 链接。它无法运行,因为代码非常大,我无法在 fiddle 中重新创建问题,但我尝试尽可能多地对其进行注释。
第二次编辑。
所以我做了一些console.log()。我在 elem.find('.SomeElement').append(el);
后面放了一个 console.log() 和一个 console.log('just print this')
在指令 Controller 内。看起来元素是在调用指令的 Controller 之前在 DOM 中创建的。这意味着所有 DOM 元素都是在分配范围之前创建的。
我错了吗?
最佳答案
问题是您每次都在同一范围内分配指令数据,因此您会覆盖以前的对象。
如何在循环开始时移动范围创建并将对象分配给新创建的范围?
此外,我还颠倒了 DOM 追加调用和 $compile 调用。根据我的经验,最好这样做(但我可能是错的)。
for(i = 0; i < trueTest.length; i++) {
var scope = $scope.$new();
var test = trueTest[i];
scope.directiveData = {
blockId: test.blockId,
dataType: test.dataType,
type: test.type,
directiveType: test.directiveType
};
var el = $("<my-directive block-id='{[{ directiveData.blockId }]}' block-data-type='{[{ directiveData.dataType }]}' block-type='{[{ directiveData.type }]}' block-directive-type='{[{ directiveData.directiveType }]}'></my-directive>");
elem.find('.SomeElement').append(el);
$compile(el)(scope);
}
我还没有测试过它,但它应该更接近工作。
关于javascript - Angular $compile 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28772822/