javascript - Why does my Angular.js controller executes its function twice in the following code? -


i have ng-repeat looping through array of objects belongs somecontroller:

<div ng-controller="somecontroller actrl">   <div ng-repeat="category in actrl.categories">     <p ng-show="actrl.checkshouldbedisplayed(category)">{{category.name}}</p>   </div> </div> 

the controller defined as:

app.controller('somecontroller', function() {  this.categories = [{   "name": "one", }, {   "name": "two", }, {   "name": "three", }, {   "name": "four", }];  this.counter = 0;  this.checkshouldbedisplayed = function(channel) {   this.counter = this.counter + 1;   console.log("executing checkshouldbedisplayed " + this.counter);   return true; };  });  

i expect checkshouldbedisplayed function count 4 there 4 elements in somecontroller.categories array. instead counts 8 - check here: http://plnkr.co/edit/dyvm49klltgof9o92jgb (you'll need @ console in browser see log). how can around behaviour? cheers!

this expected; directive ng-repeat repeat many times framework feels right; called dirty checking , can read bit more in this post.

for reason, better think declaratively rather imperatively. in other words, method checkshouldbedisplayed should says on tin , not rely on number of times called. if need perform aggregation or manipulation of sort, should done elsewhere in controller.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -