【问题标题】:directive for array without using ng-repeat不使用 ng-repeat 的数组指令
【发布时间】: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


【解决方案1】:

虽然我同意@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 相比有多少。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    • 2013-01-01
    相关资源
    最近更新 更多