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