In Angularjs, it is sometimes necessary to monitor a variable in scope because changes in variables affect the display of some interface elements. Sometimes, you also want to invoke 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 the JQ button state
<p >counter: {{counter}}</p>
Above, we hope:
Jqbtnstate variable value in scope if False let the button with ID jqbtn disabled
Click on the button with ID jqbtn to invoke a method in scope to allow the variable counter in scope to increase by 1
We might write this:
$ (' #jQBtn '). On ("click", Function () {
console.log ("JQuery button clicked");
The question to consider is:
//How to invoke a method in scope here, so that the variable counter of scope is increased by 1
})
...
Myapp.controller ("Ngctrl", function ($scope) {
$scope. counter = 0;
Here, how to let the jqbtnstate variable value change to tell the outside?
$scope. jqbtnstate = false;
$scope. Jqbtnclick = function () {
$scope. counter++
}
In fact, using the $watch method you can monitor the change of a variable in scope and call the callback function when the change occurs.
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, the button with ID jqbtn is disabled when the Jqbtnstate variable value is false.
How does the outside world invoke the scope method?
--Get scope first, then use the $apply method to invoke the method within scope.
$ (' #jQBtn '). On ("click", Function () {
console.log ("JQuery button clicked");
var scope = angular.element (ngsection). scope ();
Scope. $apply (function () {
scope.jqbtnclick ();
});
Above, by obtaining scope, the Jqbtnclick method within scope is invoked using the $apply method to increase the variable counter of scope by 1.
The above mentioned is for the ANGULARJS to monitor the scope variable as well as the external call scope method related knowledge, hope to be helpful to everybody.