如何限制角度摘要仅影响/重新渲染一个组件/指令

2024-02-25

我正在开发一个有角度的应用程序/网站,现在才意识到,每当触发模型更改/摘要时,它都会导致整个页面重新渲染,这看起来既浪费又缓慢。

有没有办法导致/限制摘要仅影响它所使用的指令/控制器。

例如,如果我有一个带有 $interval 的“时钟”指令来计算页面上的毫秒数

$scope.page_stats = {"ms_on_page": 0};
$interval(function() {
    $scope.page_stats.ms_on_page+= 30;
}, 30);

我的应用程序布局如下所示

<body>
    <clock-directive></clock-directive>//<--gets rendered every 30ms
    some other html
    <some-slow-render-directive></some-slow-render-directive>
    // ^-- also gets rendered every 30ms
</body>

我如何阻止慢指令每 30ms 更新自身/其模板,并将时钟间隔摘要限制为时钟指令,因为我知道它不会在页面的任何其他部分使用。 (这不是我的实际应用程序,只是一个示例来说明我的问题)


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.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何限制角度摘要仅影响/重新渲染一个组件/指令 的相关文章