Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firing $watch event manually in angularjs

I use this code:

$scope.$watch('message', function()
{
    // the code
});

Is there any way to fire change event of message manually, so the code will be executed?

like image 959
Draex_ Avatar asked Jul 01 '13 20:07

Draex_


People also ask

How do I use $Watch in AngularJS?

When you create a data binding from somewhere in your view to a variable on the $scope object, AngularJS creates a "watch" internally. A watch means that AngularJS watches changes in the variable on the $scope object. The framework is "watching" the variable. Watches are created using the $scope.

How are apply () Watch () Digest () different in AngularJS?

$apply() function will execute custom code and then it will call $scope. $digest() function forcefully to check all watch list variables and update variable values in view if any changes found for watch list variables. In most of the time angularjs will use $scope.

What does rootScope digest do?

$digest(), $rootScope. $apply(). It updates the data binding. It iterates through all the watches and checks any value updated.

Which among the following function registers a listener call back to be executed whenever the watchExpression changes?

$watch(watchExpression, listener, [objectEquality]); Registers a listener callback to be executed whenever the watchExpression changes. The watchExpression is called on every call to $digest() and should return the value that will be watched.


Video Answer


2 Answers

Few options:

  1. Use $scope.$apply() to run the digest loop which call all of the watch expressions

  2. Put you inner watch code inside a function and call it manually

  3. Change messages :)

like image 165
Shai Reznik - HiRez.io Avatar answered Oct 23 '22 10:10

Shai Reznik - HiRez.io


Another option here is declaring the function separately and using $scope.watch with the pointer.

var watchFunction = function(){
    // the code
}

$scope.$watch('message',watchFunction);

watchFunction();
like image 21
robstarbuck Avatar answered Oct 23 '22 09:10

robstarbuck