Home > Web Front-end > JS Tutorial > body text

Monitor Scope variables and externally call Scope methods in AngularJS_AngularJS

WBOY
Release: 2016-05-16 15:18:33
Original
1442 people have browsed it

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> 
Copy after login

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
})
Copy after login

...

myApp.controller("NGCtrl", function($scope){
$scope.counter = 0;
//这里,怎么让jQBtnState变量值发生变化告之外界呢?
$scope.jQBtnState = false;
$scope.jQBtnClick = function(){
$scope.counter++;
}
}) 
Copy after login

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++;
}
})
Copy after login

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();
});
}) 
Copy after login

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.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template