In AngularJS, you sometimes need to monitor a variable in Scope, because the variable changes will affect the display of some interface elements, next, we will use this article to introduce AngularJS to monitor Scope variables and call Scope Methods externally. For more information, see AngularJS. Sometimes you need to monitor a variable in Scope, the variable changes will affect the display of some interface elements. Sometimes, you also want to call a method of Scope through jQuery.
For example:
jQ Button
Toggle jQ button state
Counter: {{counter}}
We hope that:
● Disable the jQBtnState variable value in Scope if it is set to false and the id is set to jQBtn.
● Click the jQBtn button to call a method in Scope to increase the counter variable in Scope by 1.
We may write as follows:
$ ('# JQBtn '). on ("click", function () {console. log ("JQuery button clicked"); // The question to consider is: // how to call a method in Scope to increase the counter variable of Scope by 1 })
...
MyApp. controller ("NGCtrl", function ($ scope) {$ scope. counter = 0; // How can I change the value of jQBtnState to the outside world? $ Scope. jQBtnState = false; $ scope. jQBtnClick = function () {$ scope. counter ++ ;}})
In fact, you can use the $ watch method to monitor the changes of a variable in the Scope. When a change occurs, the callback function is called.
myApp.controller("NGCtrl", function($scope){$scope.counter = 0;$scope.jQBtnState = false;$scope.$watch("jQBtnState", function(newVal){$('#jQBtn').attr('disabled', newVal);});$scope.jQBtnClick = function(){$scope.counter++;}})
If the value of jQBtnState is false, the jQBtn id button is disabled.
How does one call the Scope method?
-- Obtain the Scope first, and then use the $ apply method to call the methods in the Scope. $ ('# JQBtn '). on ("click", function () {console. log ("JQuery button clicked"); var scope = angular. element (ngSection ). scope (); scope. $ apply (function () {scope. jQBtnClick ();});})
The preceding Code uses the $ apply method to call the jQBtnClick method in the Scope to increase the counter variable of the Scope by 1 by obtaining the Scope.
The above describes how to monitor Scope variables and call Scope Methods externally in AngularJS.