在angularjs中,有时候需要监视scope中的某个变量,因为变量的改变会影响一些界面元素的显示。有时,也希望通过jquery调用scope的某个方法。
比如以下场景:
jq button
toggle jq button statecounter: {{counter}}
以上,我们希望:
● scope中的jqbtnstate变量值如果为false让id为jqbtn的按钮禁用
● 点击id为jqbtn的按钮调用scope中的某个方法让scope中的变量counter自增1
我们可能会这样写:
$('#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++;}})
其实,使用$watch方法可以监视scope某个变量的变化,当变化发生调用回调函数。
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++;}})
以上,当jqbtnstate变量值为false的时候就会禁用id为jqbtn的按钮。
外界如何调用scope的方法呢?
--先获取scope,然后使用$apply方法调用scope内的方法。$('#jqbtn').on(click, function(){console.log(jquery button clicked);var scope = angular.element(ngsection).scope();scope.$apply(function(){scope.jqbtnclick();});})
以上,通过获取scope,使用$apply方法调用scope内的jqbtnclick方法使scope呢的变量counter自增1。
以上所述是针对angularjs中监视scope变量以及外部调用scope方法 的相关知识,希望对大家有所帮助。