Avoid unnecessary evaluation of bound values in Angular.js

♀尐吖头ヾ 提交于 2019-12-24 14:55:31

问题


Have an angular.js directive that renders as a table. Most of the time, the table is small, so performance is not an issue.

But sometimes, the table has many rows (e.g. thousands), so rendering every row is expensive, as each bound value appears to be evaluated twice, and there are a lot of bound values. And Angular seems to evaluate this table a lot, only to find that all of the values in it are unchanged and thus need not be rerendered, paralyzing the application needlessly.

For instance, the entire table appears to be re-revaluated when the value of $scope.showMenu changes on mouseenter / mouseleave.

Is there a way to tell Angular that the entire table is dependent on some other value, say, $scope.checksum thus if that doesn't change, then the entire table doesn't change?

<div class="header" ng-mouseenter="showMenu=true" ng-mouseleave="showMenu=false">
   <!-- show dropdown menu only when hovering over the header -->      
   <span ng-if="showMenu" class="menu dropdown" >  ... menu content goes here...</span>

   <h2>{{getTitle()}}</h2> 
   <p>{{description}}</p>
</div>

<table>
   <tr ng-repeat="key in rowKeys">  
      <td title="{{getRowItem(key)|pretty">{{getRowItem(key)|abbreviated}}</td>
      <td>{{getRowValue(key)|number</td>
  </tr>
enter code here
   </tr>
</table>

回答1:


If you're using Angular 1.3 and the data in your table is not updated in other moment you must try bind once.

    <tr ng-repeat="key in ::rowKeys">
      <td>{{::key}}</td>
    </tr>

Also ng-mouseenter and ng-mouseleave generate more $watchers, I recommend you use CSS rules to make this effect in your menu.



来源:https://stackoverflow.com/questions/20625395/avoid-unnecessary-evaluation-of-bound-values-in-angular-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!