We have the following directive:
app.directive("counterWidget",function(){
return{
restrict:"E",
scope:{
startnumber: '=',
resetter: '='
},
link:function(scope,elem,attr){
scope.f = attr.startnumber;
scope.add = function(){
scope.f++
}
scope.remove = function(){
scope.f--
}
scope.reset = function(){
scope.f = attr.startnumber
scope.$parent.triggerReset()
}
scope.$watch(function(attr) {
return attr.resetter
},
function(newVal) {
if (newVal === true) {
scope.f = attr.startnumber;
}
})
},
template:"<button ng-click='add()'>more</button>"+
"{{f}}"+
"<button ng-click='remove()'>less</button> "+
"<button ng-click='reset()'>reset</button><br><br>"
}
})
This directive has a clock function that monitors the reset attribute for changes. This attribute is triggered by this function in the controller:
$scope.triggerReset = function () {
$scope.reset = true;
console.log('reset')
$timeout(function() {
$scope.reset = false;
},100)
}
The question came up - maybe $ watch 'miss'? If the timeout is too short or ... I don’t know ... something else is causing it to hang for some reason, can it not catch the switch?
I have the following demo:
Plunker
I set the timeout to 1 ms and even deleted it all together and it still resets the penalty. But can there be a situation when $ watch becomes unreliable?
source
share