<\/script>')

Can $ watch 'miss'?

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>&nbsp"+
             "<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?

0
source share
1 answer

No. You can even set it to 0 ms and it will catch anyway.

$timeout , , , $digest .

$evalAsync, , .

. : fooobar.com/questions/181436/...

: , $timeout. $timeout(fn, 50, false) ( false ), $apply "" . $timeout: https://github.com/angular/angular.js/blob/master/src/ng/timeout.js#L64

0

Source: https://habr.com/ru/post/1584220/


All Articles