Reputation: 5930
Could someone explain to me why I get twice the alert message
of the following code?
<div ng-app="scopeExample" ng-controller="MyController as ctrl">
<input id="box" ng-model="ctrl.num"> {{ctrl.show_num()}}
</div>
<script>
angular.module('scopeExample', [])
.controller('MyController', MyController);
function MyController() {
this.num=12;
}
MyController.prototype.show_num=function(){
alert(this.num);
};
</script>
Upvotes: 0
Views: 31
Reputation: 983
Here is a plunkr - https://run.plnkr.co/wFWMLiO9mqQu2LlU/
It runs twice for you because the event (DOMContentLoaded) is propagated to all the parent elements as well. In this case it only include the <div>
tag. If you nest this under other tags, it will fire more times.
You should be using the angular $scope instead of prototyping and using the this variable.
Upvotes: 0
Reputation: 691735
AngularJS evaluates all the expressions in a page multiple times, at each digest loop, until the result is stable.
What you're seeing is perfectly normal.
But expressions should not have side-effects like alerting, or modifying values.
Upvotes: 2