监听服务$watch1、不需要在控制器脚本中注入,直接使用2、监听任何想要监听的NG变量的值,并在这个值改变的时候调用回调函数语法:$scope.$watch('想要监听的NG变量(不需要加$scope.)或字符串',回调函数)3、开启深度监视,如监视数组内容的添加等,不开启深度监视不会调用回调函数$scope.$watch('想要监听的NG变量(不需要加$scope.)或字符串',回调函数,true)
代码示例:
<html ng-app='app' ng-controller='main' ><head><meta charset="utf-8"><meta name='viewport' content='width=device-width,user-scalable=no,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0'><title ng-bind='mainTitle'></title><script src='js/angular.js'></script><script src='js/angular.route.min.js'></script><style></style></head><body ><input type="text" ng-model='in'><div ng-controller='d1'><input type="text" ><button ng-click='check()'>点击</button><p>{{arr}}</p></div><script>var app=new angular.module('app',[]);app.controller('main',['$scope',function($scope){$scope.in='';$scope.$watch('in',function(){console.log('他变了')});}])//深度监视app.controller('d1',['$scope',function($scope){$scope.arr=[1,2,3];$scope.$watch('arr',function(){console.log('变了')},true)$scope.check=function(){this.arr.push(1);}}])</script></body></html>
如果觉得《Angular 事件监听$scope.$watch》对你有帮助,请点赞、收藏,并留下你的观点哦!