Angular 会(通常)重新渲染所有内容$rootScope.$digest()
,这被称为$scope.$apply()
, $interval
, 等等。
然而,有is您可以应用一种优化策略,仅重新渲染适用的部分(高频更新)。
首先,将你的观点分成不同的范围。例如,每 30 毫秒更新一次的计数器可以位于其自己的控制器中,通过 Heavy 指令将其与范围分开。
然后,使用非角度间隔(例如setInterval()
) 更新你的值,然后调用$scope.$digest()
手动。
例如:
JS:
app.controller('MainCtrl', function($scope, $interval) {
// this is our "heavy" calculation function
// it displays a Unix timestamp, which should change
// every second if the function is continously executed
$scope.calc = function() {
// get time in seconds
return Math.floor(new Date().getTime() / 1000);
};
});
app.controller('ChildCtrl', function($scope, $interval) {
$scope.counter = 0;
// don't use $interval, it'll call $rootScope.$apply()
// uncomment this and comment the setInterval() call
// to see the problem
//$interval(function() { $scope.counter++; }, 1000);
setInterval(function() {
$scope.counter++;
// digest only our scope, without re-rendering everything
$scope.$digest();
}, 1000);
});
HTML:
<body ng-controller="MainCtrl">
<!-- pretend this is our calculation that occurs often -->
<p ng-controller="ChildCtrl">Interval counter: {{ counter }}</p>
<!-- pretend this is our heavy calculation that we don't want to occur often -->
<p>Heavy calc: {{ calc() }}</p>
</body>
Plunker http://plnkr.co/edit/iiek1WWDm2DKH2vjFiQ9
在这种情况下,假设calc()
是重指令。您会注意到它仅评估一次,而不是每次计数器更新时。但是,如果您使用$interval
,每次计数器更新时它都会更新。
请注意,您must use $scope.$digest()
- 如果你使用$scope.$apply()
,它会调用$rootScope.$digest()
,这将更新所有内容。
进一步阅读here https://github.com/angular/angular.js/issues/5583.