Why does the AngularJS filter work only once?

Consider the following example:

    angular.module('app', []).controller('TestController', function($scope) {
      $scope.getText = function() {
          console.log('getting text');
          return 'text';
      };
  }).filter('text', function() {
      return function() {
          console.log('text filter');
          return 'text';
      };
  });
 

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<div ng-app="app" ng-controller="TestController">
    <p>{{getText()}}</p>
    <p>{{'' | text}}</p>
</div>
Run codeHide result

Note that the function getText()is executed twice, while the filter only works once. I assume the function getText()runs twice to make sure the model is now stable. Why isn't the same behavior for a filter?

+4
source share
5 answers

The documentation is pretty clear on this:

In templates, filters are only executed when their inputs have changed . This is more efficient than filtering for each $ digest, as is the case with expressions.

Here is the source.

+5

Cosmin - , (, , - ) - getText(), , , , ... .


EDIT. , - , getText .

angular.module('app', []).controller('TestController', function($scope) {
  $scope.foo = 'bar';
  $scope.getText = function() {
    console.log('getting text');
    $scope.foo += 'a';

    return 'text';
  };
}).filter('text', function() {
  return function() {
    console.log('text filter');
    return 'text';
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<div ng-app="app" ng-controller="TestController">
  <p>{{getText()}}</p>
  <p>{{foo | text}}</p>
</div>
Hide result
+3

, AngularJS / (), / / HTML.

AngularJS: - . , $digest, .

:

  • , . , , $ digest, , .
  • , $stateful, $digest. . Stateful. , AngularJS $stateful.
+1

,

. , $digest, .

:

, , . , , $digest, , .

, $stateful, $digest. . Stateful. , AngularJS $stateful.

, , . '' {} , ;)

0

, , . - ''. Angular INPUT () . .

, , .

, this, , , - .

, , :

{{getText() | text}}
0

Source: https://habr.com/ru/post/1672009/


All Articles