避免在 Angular.js 中对绑定值进行不必要的评估 [英] Avoid unnecessary evaluation of bound values in Angular.js

查看:23
本文介绍了避免在 Angular.js 中对绑定值进行不必要的评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个呈现为表格的 angular.js 指令.大多数时候,表很小,所以性能不是问题.

但有时,表有很多行(例如数千行),因此渲染每一行的开销很大,因为每个绑定值似乎都被评估了两次,并且有很多绑定值.而且 Angular 似乎对这张表评估了很多,结果发现里面的所有值都没有改变,因此不需要重新渲染,不必要地使应用程序瘫痪.

例如,当 $scope.showMenu 的值在 mouseenter/mouseleave 上发生变化时,整个表格似乎被重新评估.

有没有办法告诉 Angular 整个表依赖于其他一些值,比如 $scope.checksum 因此如果它没有改变,那么整个表也不会改变?

<!-- 仅在将鼠标悬停在标题上方时显示下拉菜单 --><span ng-if="showMenu" class="菜单下拉菜单" >...菜单内容在这里...</span><h2>{{getTitle()}}</h2><p>{{描述}}</p>

<表格><tr ng-repeat="key in rowKeys"><td title="{{getRowItem(key)|pretty">{{getRowItem(key)|abbreviated}}</td><td>{{getRowValue(key)|number</td></tr>在此处输入代码</tr>

解决方案

如果您使用的是 Angular 1.3 并且您的表中的数据在其他时间没有更新,您必须尝试绑定一次.

 <td>{{::key}}</td></tr>

还有 ng-mouseenter 和 ng-mouseleave 生成​​更多 $watchers,我建议您使用 CSS 规则在您的菜单中实现此效果.

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>

解决方案

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.

这篇关于避免在 Angular.js 中对绑定值进行不必要的评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆