AngularJS monitors Scope variables and calls the Scope method externally.
In AngularJS, you sometimes need to monitor a variable in the Scope, because 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:
<div><button id="jQBtn">jQ Button</button></div><div id="ngSection" ng-controller="NGCtrl"><input type="checkbox" ng-model="jQBtnState"/> Toggle jQ button state<p>Counter: {{counter}}</p></div>
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.
Articles you may be interested in:
- $ Scope method User Guide in angularJS
- In-depth exploration of the Scope object supertutorial in AngularJS framework