范围功能和过滤器

AngularJS 具有摘要循环,每次运行摘要周期时都会在视图和过滤器中执行所有功能。每当更新模型时都会执行摘要循环,它会降低你的应用程序速度(在页面加载之前可以多次点击过滤器)。

你应该避免这个:

<div ng-controller="bigCalulations as calc">
  <p>{{calc.calculateMe()}}</p>
  <p>{{calc.data | heavyFilter}}</p>
</div>

更好的方法

<div ng-controller="bigCalulations as calc">
  <p>{{calc.preCalculatedValue}}</p>
  <p>{{calc.data | lightFilter}}</p>
</div>

控制器样本的位置是:

.controller("bigCalulations", function(valueService) {
  // bad, because this is called in every digest loop
  this.calculateMe = function() {
    var t = 0;
    for(i = 0; i < 1000; i++) {
      t = t + i;
    }
    return t;
  }
  //good, because it is executed just once and logic is separated in service to    keep the controller light
  this.preCalulatedValue = valueService.caluclateSumm(); // returns 499500
});