【发布时间】:2013-01-31 23:13:32
【问题描述】:
我又一次偶然发现ng-repeat 的性能很慢,并且不知道如何构建一个指令来在不使用ng-repeat 任何地方(甚至在模板中)的情况下呈现一个元素数组
那么,你们是怎么做到的呢?
即使我遍历数组,对每个元素都使用模板:
.directive('foo', function($parse, $compile) {
return {
restrict: 'E',
scope: { items: '=myarray' },
link: function (scope, element, attrs){
var tmplt = '<div> {{name}} </div>';
scope.items.forEach(function(){
element.append(tmplt(scope));
// now I'd like to have a scope of that element,
// and pass it into the template, and use properties related
// only to that element
// but I don't know how to get a scope for a child element
});
scope.$watch(attrs.myarray, function(value) { console.log('something change'); })
}
}});
如果我选择为所有元素使用一个模板,那么我别无选择,只能在其中使用 ng-repeat,它会创建 ngRepeatWatchers,一切都会再次变慢。
【问题讨论】:
-
每个 {{name}} 都会设置一个 $watch。我看不出这会比 ng-repeat 快得多,特别是考虑到您还希望每个项目都有一个单独的范围。数组需要动态改变吗?您可以对数据进行分页吗?
标签: angularjs angularjs-directive ng-repeat