Consider:
angular
.module('app', [])
.controller('MainController', function($scope) {
$scope.$watch('bool', function(newVal, oldVal) {
});
console.log($scope);
});
and
<body ng-controller='MainController'>
<p ng-class="{'blue': bool, 'red': !bool}">ngClass</p>
<p ng-show='bool'>ngShow</p>
<input type='checkbox' ng-model='bool' />
</body>
It seems that there are 3 watchers being created:
- From
$scope.$watch
. - From
ngShow
. - From
ngClass
.
(Note: directives involved in data binding use $scope.$watch internally.)
I would have thought that since they're all watching the bool
property, there'd only be one watcher and it'd have multiple listener callbacks.
Edit: is it the case that it's saying, "Has bool
changed? If so run cb1
. Has bool
changed? If so run cb2
. Has bool
changed? If so run cb3
." Or is it the case that it's saying, "Has bool
changed? If so run cb1
, cb2
, and cb3
." If the former, why do that over the latter?
Questions:
- Is my interpretation correct? Are there actually multiple watches being registered?
- What are the implications for performance?
- Bonus: if my interpretation is correct and multiple watchers are being added, why would it be designed like this? Why look for changes to
bool
3 times instead of 1?
Example for 2) - say you want to make sure that two passwords in a form match, and if they don't, show an error. Assume that you already have:
ng-class="{invalid: myForm.myInput1.$touched && ctrl.myInput1 != ctrl.myInput2}"
Say you want to use $setValidity
to update the validity of the form. Might it be a good idea to do:
ng-class="{invalid: myForm.myInput1.$touched && ctrl.functionToCheckInputs(myForm)}"
and call $setValidity
inside of functionToCheckInputs
rather than using $scope.$watch
and doing $setValidity
inside of it? Because the latter adds an additional watcher (presumably).