我再一次偶然发现了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并且一切都会再次变慢。
答案 0 :(得分:0)
虽然我同意@Mark,但这是你问题的肮脏解决方案:
http://plnkr.co/edit/wxM8mSoNsRGXBJUao5Xb?p=preview
我们的想法是创建孤立的子范围:
scope.items.forEach(function(item){
var childScope = scope.$new(true);
angular.extend(childScope, item);
element.append($compile(tmplt)(childScope));
});
不要忘记在每次刷新时删除这些子范围。
并且这个解决方案需要进行基准测试,看它是否比ngRepeat更快,多少。