I'm coming from Knockout and I'm trying to understand how Angular updates the scope. I'm a bit confused as to why a function defined on the scope (e.g. $scope.doStuff = function()
) gets executed on every single scope refresh.
Plnkr link: http://plnkr.co/edit/YnvOELGkRbHOovAWPIpF?p=preview
For example:
HTML
<div ng-controller="one">
<input type="text" ng-model="a">
{{b()}}
</div>
JS
angular.module('test', [])
.controller('one', ['$scope', function ($scope) {
$scope.a = 'one';
$scope.b = function () {
console.log('b has executed');
}
}])
So whenever an event happens in the input form field for $scope.a
, function $scope.b
gets executed. Why does that happen? There are no dependencies on that function, it seems inefficient that it is always refreshing.
If I add another controller in the same structure, like such:
HTML
<div ng-controller="one">
<input type="text" ng-model="a">
{{b()}}
</div>
<div ng-controller="two">
<input type="text" ng-model="x">
{{y()}}
</div>
JS
angular.module('test', [])
.controller('one', ['$scope', function ($scope) {
$scope.a = 'one';
$scope.b = function () {
console.log('b has executed');
}
}])
.controller('two', ['$scope', function ($scope) {
$scope.x = 'two';
$scope.y = function () {
console.log('y has executed');
}
}])
Every time I update $scope.a
in controller one
the output is:
b has executed
y has executed
Why is controller two
executing $scope.y
? I thought creating a new controller creates a new child scope. Is it because the child scopes are linked to the parent scope?
More interestingly, if I update $scope.x
in controller two
then the output is:
b has executed
y has executed
b has executed <-- a second time... what?
Why does function $scope.b
get executed a second time?
So why do functions in Angular get executed on every scope refresh?