-09-23
今天周五~周五~[ 转圈 ]
今天来说的是ng中内置的使用较多的函数 $watch
<select class="form-control" ng-model="name" ng-options="a.id as a.name for a in names"></select>
在这说一下
ng-options这种写法,是将names这个数组中的name值显示在下拉列表中,或者是a as a.name for a in names 这无非区别是是将整个对象当作参数处理还是具体到某个属性。
angular.module('myApp', []).controller('appCtrl', appCtrl);appCtrl.$Inject = ['$scope', '$timeout']; //init modulefunction appCtrl($scope, $timeout) { //定义$scope.name = null;$scope.names = [{id: 1,name: 'aaa'}, {id: 2,name: 'bbb'}, {id: 3,name: 'ccc'}];$scope.$watch('name', function (newVal, oldVal) {console.log(newVal);console.log(oldVal);});}
定义一个names数组,当改变下拉列表中的值时,就会触发$watch函数来监听name的变化。
当然此种方法只适用于监听一个属性值的情况,若要监听多个,则需要使用$watchgroup来实现。
$scope.news = null;news.get().then(function(data) {$scope.news = data;});$scope.persons = null;person.get().then(function(data) {$scope.persons = data;});$scope.initView = function() {};
假如我现在从news和person接口get到数据,我想同时监听news和person的变化
$scope.$watchGroup(["news", "persons"], function(newVal, oldVal) {//注意:newVal与oldVal都返回的是一个数组var news1 = newVal[0];var person1 = newVal[1];if (news1 != null && person1 != null) {$scope.initView();}});
还有一个$watchCollection,在实际的应用中 比较适用于监控数组等这类对象。
刚才看了书以后说,如果想要监控多个东西,也可以使用$watch来办到。
(1)监控把这些属性连接起来之后的值
假如在你的作用域中存在一个things对象,它带有两个属性a和b,当这两个属性发生变化时执行callMe()函数
</pre><pre name="code" class="plain">$scope.$watch('things.a+things.b',callMe(...))
此时,a和b也可以属于不同的对象,只要需要,这个列表可以无限长,如果列表非常长,你就需要一个函数来返回连接之后的值,而不是以来一个表达式来完成此逻辑。
(2)监控这个things对象上的所有属性
$scope.$watch('things',callMe(...),true);
这里给第三个参数一个true值,请求angular遍历things的属性,然后当其中任何一个属性发生变化时,调用callMe(),这一机制在数组上的运行方式和在对象上的运行方式相同。
如果觉得《$watch的用法》对你有帮助,请点赞、收藏,并留下你的观点哦!