我已经重新研究了这个问题几个小时,最后我在 plunker 上重现了它。
这是我的问题:
当使用外部资源作为模板的自定义指令与ng-repeat结合使用时,模型更改时视图未正确呈现。
在我的示例中,单击链接将替换模型,但旧数据尚未清理。
如果我使用 template: 'stringTemplate'
而不是 templateUrl: 'urlToTemplate'
,它就可以正常工作。仍然不知道这是错误还是什么...
部分代码:
angular.module('test', [])
.run(function($rootScope) {
$rootScope.topics = [{
content: 'Click here to change reply',
replys: [{
content: 'Reply test...',
}]
}];
})
.directive('topic', function() {
return {
replace: true,
restrict: 'E',
templateUrl: 'topic.htm',
link: function(scope) {
scope.reply = function(input) {
scope.topic.replys = [{ content: '"Reply test..." should be replaced, but it's not!' }];
}
}
};
})
.directive('reply', function() {
return {
replace: true,
restrict: 'E',
// template: '<div><div ng-bind="reply.content"></div></div>' //this works fine
templateUrl: 'reply.htm' // same content
};
});
我做了一些研究,似乎你并不孤单:
https://github.com/angular/angular.js/issues/2151
用户 ishw 提到,作为快速修复:
"对于那些可能还没有意识到这一点的人来说:这是因为你的ng-repeat在你的指令模板中的根元素上。用任何元素包裹你的ng重复,它会没事的。
我用你的 plunkr 试过这个,它似乎正在工作:
<div>
<div class="topic" ng-bind="topic.content" ng-click="reply()"></div>
<div ng-repeat="reply in topic.replys"><reply></reply></div>
</div>