Bhojendra Nepal Bhojendra Nepal - 4 months ago 11
AngularJS Question

how does this break the watching value?

$scope.$watch('num',function(){
$scope.nums.push($scope.num)
})


Changing the above code breaks the watching value on clicked (I'm unclear because breakit still pushing the value to nums):

$scope.breakit = $scope.$watch('num',function(){
$scope.nums.push($scope.num)
})


But I'm unclear how does this break the watching value?

Full code:

<div ng-controller="MainController">
<div>Num: {{num}}</div>
<div>Nums: {{nums}}</div>
<button ng-click="increment()">Increment</button>
<button ng-click="breakit()">Break It</button>
</div>

var app = angular.module('app',[]);
app.controller('MainController',function($scope){
$scope.num = 0
$scope.nums = []
$scope.increment = function(){
$scope.num++;
}
$scope.breakit = $scope.$watch('num',function(){
$scope.nums.push($scope.num)
})
});


So, using
$scope.breakit
why does this stops pushing the
num
to
nums
clicking to break it button and continue clicking to increment button?

You may check this video.

Answer

The documentation for $scope.watch() says:

Returns

function() Returns a deregistration function for this listener

When you call $scope.watch(), it returns a function that you can call at any time to unregister it.

Your controller assigns that function to $scope.breakit, so when $scope.breakit is called, the watch is turned off.


Edit:

There was a question in the comments about how $scope.break pushes values to the nums array. The answer is that it doesn't. $scope.watch() takes care of that all on its own, and $scope.break is used as a way to turn that process off.

Comments