首页 > 代码库 > $watch和$observe的使用
$watch和$observe的使用
$observe 是Attribute对象的一个方法,用来监听DOM中属性值的变化。比如 attr1="{{name}}"
Attribute定义在directive中的link函数的第三个参数上。所以$observe只能用在directive中。
可以看到它的回调函数只有一个参数,就是新值。
.directive(‘myCustomer‘, function(){ return { link: function(scope, element, attrs) { attrs.$observe(‘attr1‘, function(newVal) { //.... }) } } })
总结如下:
$observe只能用在directive,$watch没有那么多限制,$watch是scope对象上的方法,所以可以用在控制器或者是directive的link方法中。
$observe只能用监听DOM属性值的变化,$watch可以监听表达式,表达式可以是一个函数或字符串。如果是字符串会使用$parse转换为函数。字符串表达式不能包含{{}}。
$observe的回调函数有newValue, $watch有oldValue和newValue
$watch和$observe的使用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。