Reputation: 319
Why is my alert being called on page load and being called twice? Is that normal behavior?
I also have a ng-click on some images in another div/controller and it is calling the alert. ????? Added below.
I have a html markup like below.
<div class="item-blue" ng-controller="ItemController as item">
<div class="col" ng-show="item.checkItem('foo')">
Then in my controller is the below.
app.controller('ItemController', function() {
this.checkItem = function(bar) {
alert(bar);
};
});
Weird!!!!
https://codepen.io/anon/pen/oBjJyw
Upvotes: 1
Views: 64
Reputation: 38121
This is because AngularJS sets up a "watch" on the expression that you use for ng-show
. It then regularly re-evaluates that expression (during something called the digest cycle) to see if the value has changed. Since your expression involves calling a function, that function will get called every time the expression gets evaluated.
This digest cycle happens extremely often, and you can't always control when it happens. As a result, only ever call functions in expressions used for things like ng-if
, ng-show
, ng-class
, etc if they just return a value (as opposed to doing something like showing an alert, changing state, etc).
Here are just some of the situations which trigger the digest (there are many more):
$scope.$apply()
or $scope.$digest()
explicitly$timeout
or $interval
As you can hopefully see, that is a lot of causes for it, so you don't want to do more work in it than required, and all the expressions it evaluates should only ever return values.
Upvotes: 2
Reputation: 100
It's a normal behavior in angular js as it seems to keep happening no matter the approach you take because of the ng-show, angular tries to check the condition (which in this case calls a method "checkItem()" which pops up an alert box) so i don't think this is as a result of any code malfunction.
Upvotes: 2
Reputation: 630
Does ItemController
appear on the page more than once? That could explain the behavior you are experiencing.
Upvotes: 0