1

我有一个指令可以用ng-repeat生成大量的html输入[type =“radio”]。他们每个人都分配了一些属性。AngularJS中的“静态”属性

基本上:

<div ng-repeat"day in days"> 
    <label ng-repeat="slot in day.slots"> 
    <input type="radio" class="{{slot.class}}" value="{{slot.value}}" ng-disabled="{{slot.disabled}}"> 
    </label> 
</div> 

的问题是,增加了角观察者每个输入单元的每个属性和它消耗了大量的资源。如果days不更改,属性不会更改。有什么办法可以使属性静态并仍然使用ng-repeat?或者我必须以其他方式生成模板?在那种情况下,当days更改时,我将如何执行并仍然重新呈现?

更新:澄清说,它不只是类属性

回答

0

尝试使用ng-class

<input type="radio" ng-class="slot.class" /> 

的守望者仍难免,但类属性未设置每次摘要发生,只有当slot.class的值更改。

编辑:更新以反映原始海报想要的。

我不确定这是否是一种很好的做法,但您可以尝试编写一个指令,通过注销所有观察者来生成一个“哑”模板。这样,只有在监视语句的结果发生变化时,您才会更新模板。

事情是这样的:

module.directive('shallowWatch', function($compile){ 
    return { 
     compile : function(tElement, tAttrs){ 
      var templateFN = $compile(tElement.html()); 
      tElement.empty(); 
      return function(scope, element, attrs){ 
       var childScope; 
       scope.watch(attrs.shallowWatch, function(){ 
        element.empty(); 
        if(childScope){ 
         childScope.$destroy(); 
        } 
        childScope = scope.$new(); 
        element.append(templateFn(childScope)); 
        traverseScope(childScope, function(scope){ 
         scope.$$watchers = []; 
        }); 
       }); 
      }; 
     } 
    }; 

    function traverseScope(target, fn){ 
     var current, next; 
     current = target; 
     do { 
      fn.apply(current, [current]); 

      //depth-first traversal pulled from angularjs core 
      if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { 
       while(current !== target && !(next = current.$$nextSibling)) { 
        current = current.$parent; 
       } 
      } 
     } while ((current = next)); 
    } 
}); 

你会使用它,像这样:

<div shallow-watch="days"> 
    <div ng-repeat"day in days"> 
     <label ng-repeat="slot in day.slots"> 
     <input type="radio" class="{{slot.class}}" value="{{slot.value}}" ng-disabled="{{slot.disabled}}"> 
     </label> 
    </div> 
</div> 
+0

对不起。我的整个问题都不清楚,那就是每个输入元素都有很多属性。 – Oscar