简体   繁体   中英

AngularJS custom filter being called twice

I've created a custom filter using AngularJS that prints out the fruits that start with a p. As far as I can tell, I've implemented the custom filter correctly.

I'm printing out a message every time the filter is called but I'm curious to why my filter is being called twice.

Looking at similar problems on stackoverflow I found one person who had a similar issue however the problem wasn't answered and was a little different.

JSFiddle Solution http://jsfiddle.net/ddemott/U3pVM/22606/

HTML Code

<body>
    <div ng-controller="ExampleCtrl" ng-app="sampleApp">
    <div class="showDiffTags" ng-repeat="val in values | myFilter:'p'">{{val.name}}</div>
    </div>
</body>

AngularJS Code

angular.module('sampleApp', []).filter('myFilter', function() {

  return function(items, firstLetter) {
    var groups = [];
    console.log("called function");
    console.log(items.length);
    for (var i = 0; i < items.length; i++) {
      if (items[i].name.substring(0, 1) == firstLetter) {
    groups.push(items[i]);
      }
    }
    return groups;
  }
}).controller('ExampleCtrl', function($scope) {
  $scope.values = [{
    name: 'apple'
  }, {
    name: 'banana'
  }, {
    name: 'orange'
  }, {
    name: 'avocado'
  }, {
    name: 'pineapple'
  }, {
    name: 'peach'
  }, {
    name: 'plum'
  }, {
    name: 'grapes'
  }, {
    name: 'mango'
  }, {
    name: 'papaya'
  }, ];
});

That is correct behaviour and it's strongly coupled with how $digest cycle works

Every time model changes the $digest is run at least twice:

  1. After model changes it runs the watchers and updates the models
  2. To check if the first $digest made changes to model, if so another digest is called up to max ten iterations then angular throw errors.

There is nothing to worry unless you have a lot of functions in templates and unstable models (changing often)

I've updated your fiddle with simple button that updates model on scope

http://jsfiddle.net/U3pVM/22610/

<button ng-click="numModel = numModel + 1">
  update model {{numModel}}
</button>

You will see that every time you click the button filter runs twice

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM