angularjs的$watch、$watchGroup、$watchCollection使用方式(转载)

如果想在controller里面随时监听一个值的变化那就用<code>$watch</code>

<p>  
<label><strong>$watch:</strong></label>
<input type="text" ng-model="name" />
</p>
$scope.$watch("name",function(newVal,oldVal){    
        console.log("new:"+newVal,"old:"+oldVal)
});

以上代码实现监听<code>name</code>属性值的变化,但是有个缺点假如要监听很多个属性值,就要写很多个<code>$watch</code>为了解决上面的问题,可以使用<code>$watchGroup</code>,这个监听器是把多个属性使用数组的形式作为第一个参数传入

<p style="margin-top: 20px">  
<label><strong>$watchGroup:</strong></label>
<input type="text" ng-model="one" />
</p>
<p>    
<label><strong>$watchGroup:</strong></label>    
<input type="text" ng-model="two"/>
</p>
$scope.$watchGroup(["one","two"], function (newVal,oldVal) {
        console.log("new:"+newVal,"old:"+oldVal);    
        //注意:newVal与oldVal都返回的是一个数组
});

<code>$watchCollection</code>是为一堆数据进行监听

<p style="margin-top: 20px"><strong>$watchCollection:</strong></p>
<ul>
<li ng-repeat="d in lang">{{d}}</li>
</ul>
$scope.lang = ['C/C++', 'Java', 'C#', 'Python'];
$scope.$watchCollection('lang', function (newVal, oldVal) {    
        console.log("new:"+newVal,"old:"+oldVal)
});

现在可以做个测试,使用<code>$timeout</code>二秒后发生变化

$timeout(function(){
        $scope.lang = ['JavaScript', 'Html5', 'Css3', 'Angularjs'];
},2000);

点击查看完整代码

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容