我使用track by子句进行ng-repeat(以优化性能)。我还有一个自定义指令,用于处理每个tr:
<tr ng-repeat="item in Products track by item.Id"
on-row-rendered="rowRendered">
app.directive('onRowRendered', function($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
debugger;
$timeout(function() {
scope.$emit(attr.onRepeatDone, element);
});
}
}
};
});
在加载期间(首先设置产品时)效果很好。但是当模型被更改时(例如其中一个项目被更新)onRowRendered的链接方法没有被调用(我调试器调用那里检查它),而更新绑定并正确地重新呈现html。
我希望AngularJs至少可以为那些已更新的项目调用它。我的期望是错的吗?我该怎么做呢?
答案 0 :(得分:1)
今天我一直在深入研究ngRepeat
控制器的代码,我很遗憾地说,但是这段代码对于正在更新的项目不起作用,因为ngRepeat
控制器不会破坏更新项的范围,它会更新范围属性($ index,$ first,$ last等),但它不会破坏范围,除非该项目需要删除。
只有在每次对集合进行更改时都会销毁并重新创建重复的所有项目的所有范围,您的代码才会起作用,但这不是ngRepeat
控制器的操作方式。 / p>
但您可能想尝试这样做:
.directive('onRowRendered', function($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
scope.$watch('item', function(){
$timeout(function() {scope.$emit(attr.onRowRendered, element);});
}, true);
}
}
});
每次添加或更改项目时都应$emit
。