In AngularJS, sometimes you need to monitor a variable in Scope, because changes in variables will affect the display of some interface elements. Sometimes, you also want to call a method of Scope through jQuery.
For example, the following scenario:
<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>
Above, we hope:
● If the jQBtnState variable value in Scope is false, disable the button with the id jQBtn
● Click the button with the ID jQBtn to call a method in Scope to increase the variable counter in Scope by 1
We might write:
$('#jQBtn').on("click", function(){ console.log("JQuery button clicked"); //需要考虑的问题是: //这里如何调用Scope中的某个方法,使Scope的的变量counter自增1 })
...
myApp.controller("NGCtrl", function($scope){ $scope.counter = 0; //这里,怎么让jQBtnState变量值发生变化告之外界呢? $scope.jQBtnState = false; $scope.jQBtnClick = function(){ $scope.counter++; } })
In fact, you can use the $watch method to monitor changes in a variable in Scope, and call the callback function when changes occur.
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++; } })
Above, when the value of the jQBtnState variable is false, the button with the id jQBtn will be disabled.
How does the outside world call Scope's methods?
--先获取Scope,然后使用$apply方法调用Scope内的方法。 $('#jQBtn').on("click", function(){ console.log("JQuery button clicked"); var scope = angular.element(ngSection).scope(); scope.$apply(function(){ scope.jQBtnClick(); }); })
Above, by obtaining the Scope, use the $apply method to call the jQBtnClick method in the Scope to increase the variable counter of the Scope by 1.
The above is the relevant knowledge about monitoring Scope variables and externally calling Scope methods in AngularJS. I hope it will be helpful to everyone.