Reputation: 1
Why my controller executes twice ?
I made many tests and it returns the same result, it can impact my application ?
<html ng-app="todoApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<script>
"use strict";
angular.module('todoApp', [])
.controller('TodoListController', function() {
var todoList = this;
var i = 0;
todoList.addTodo = function() {
console.log(1)
i++;
// return i it breaks the script
};
});
</script>
</head>
<body ng-controller="TodoListController as todoList">
{{todoList.addTodo()}}
</body>
</html>
Upvotes: 0
Views: 38
Reputation: 7490
Your controller doesn't execute twice, you function addTodo is executed twice. That happens cause angular is rendering de view twice.
Read angular $watch to underestand why {{}} are executed twice.
After a watcher is registered with the scope, the listener fn is called asynchronously (via $evalAsync) to initialize the watcher. In rare cases, this is undesirable because the listener is called when the result of watchExpression didn't change. To detect this scenario within the listener fn, you can compare the newVal and oldVal. If these two values are identical (===) then the listener was called due to initialization.
Upvotes: 0
Reputation: 5020
It's a problem with the Angular digest cycle. addTodo()
would be executed as frequently as that cycle runs, anything from 1 to several iterations.
in your Angular template expressions ({{}}
), bind to scope variables, not functions unless you know what you do (that is only bind to idempotent getter functions). And compute the value of those variables in your controller. Like this:
<html ng-app="todoApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<script>
"use strict";
angular.module('todoApp', [])
.controller('TodoListController', function() {
var todoList = this;
var i = 0;
todoList.addTodo = function() {
console.log(1)
i++;
return i;
};
todoList.todo = todoList.addTodo();
});
</script>
</head>
<body ng-controller="TodoListController as todoList">
{{todoList.todo}}
</body>
</html>
Upvotes: 1