我正在为指令编写测试,执行测试时模板(已正确加载)呈现为 <!-- ng-repeat="foo in bar" -->
对于初学者来说,代码的相关部分:
测试
...
beforeEach(inject(function ($compile, $rootScope, $templateCache) {
var scope = $rootScope;
scope.prop = [ 'element0', 'element1', 'element2' ];
// Template loading, in the real code this is done with html2js, in this example
// I'm gonna load just a string (already checked the problem persists)
var template = '<strong ng-repeat="foo in bar"> <p> {{ foo }} </p> </strong>';
$templateCache.put('/path/to/template', [200, template, {}]);
el = angular.element('<directive-name bar="prop"> </directive-name>');
$compile(el)(scope);
scope.$digest(); // <--- here is the problem
isolateScope = el.isolateScope();
// Here I obtain just the ng-repeat text as a comment
console.log(el); // <--- ng-repeat="foo in bar" -->
}));
...
指令
该指令相当简单,这不是问题(在测试之外一切正常):
app.directive('directiveName', function () {
return {
restrict : 'E',
replace : true,
scope : {
bar : '='
},
templateUrl : '/path/to/template', // Not used in this question, but still...
});
更多细节:
- 指令在测试之外工作正常
- 如果我将模板更改为更简单的内容,例如:
<h3> {{ bar[0] }} </h3>
测试工作正常 - rootScope 已正确加载
- isolateScope 结果为
undefined
最佳答案
如果您查看 Angular 为 ng-repeat
创建的生成输出,您会在 html 中找到注释。例如:
<!-- ngRepeat: foo in bars -->
这些注释是由编译函数创建的——查看 Angular 源:
document.createComment(' ' + directiveName + ': '+templateAttrs[directiveName]+' ')
如果您调用 console.log(el);
,您将获得创建的评论。如果您以这种方式更改输出,您可以检查一下:console.log(el[0].parentNode)。你会看到有很多childNodes:
如果您在测试之外使用该指令,您将不会意识到这个问题,因为您的元素 directive-name
将被完整创建的 DocumentFragment
替换。另一种解决问题的方法是为指令模板使用包装元素:
<div><strong ng-repeat="foo in bar"> <p> {{ foo }} </p> </strong></div>
在这种情况下,您可以访问 div
元素。
关于javascript - $digest 渲染 ng-repeat 作为注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21478532/