2016-05-24 72 views
3

我有一个ng-repeat,它像一个开关条件,告诉要渲染哪个模板。我正在使用ng - 如果在ng-repeat内部来实现这一点。问题?它仍然在评估ng中的模板 - 即使条件评估为false,导致整个事情变得缓慢。有没有一种方法可以防止在ng中评估模板 - 如果其条件评估为false?

<div ng-repeat="i in ..."> 
    <div ng-if="i == 'something1'"> 
    if this is false, do not evaluate this entire stuff 
    .... some complex template goes here 
    </div> 
    <div ng-if="i == 'something2'"> 
    if this is false, do not evaluate this entire stuff 
    .... another complex template goes here 
    </div> 
</div> 

如果里面每个NG-如果是复杂的,有20毫微克,如果里面NG重复,只有一个NG-如果计算结果为真,那么其他19个模板会浪费计算资源的模板。

我能做些什么来减轻这种影响,而不诉诸于程序化方法,并且保持呈现模板的双向绑定?

回答

0

如果条件为false,ng-if会从HTML中删除项目,因此某些渲染&评估可能会在发生之前发生。如果你在ng-if中嵌入ng-include,那么你通过ng-include加载的模板从不被评估。

事情是这样的:

<body ng-app="app"> 
    <div ng-controller="myController as ctrl"> 
     <div ng-if=true> 
      Hi 
      <div>{{ctrl.log(true)}}</div> 
     </div> 
     <div ng-if=false> 
      Bye 
      <ng-include src="foo.html"></ng-include> 
      <div>{{ctrl.log(false)}}</div> 
     </div> 

    </div> 
    <script> 
     angular.module('app', []).controller("myController",myController); 

     function myController($scope){ 
      var ctrl = this; 

      ctrl.log=function(val) {  
       console.log(val); 
       return val; 
      } 
     }; 
    </script> 
</body>