我试图在我的自定义指令中使用单向绑定进行一些数据操作,但是我收到了#34; undefined"第一次。我应该怎么做指令而不是使用$ watch?
示例:
<one val={{arr[1].value}}> </one>
<two val="arr[0].value"> </two>
&#13;
指令:
.directive('one', function(){
return {
restrict: 'E',
scope: {
val:'@'
},
template: '<div> 1111 {{val}} </div>' ,
link: function (scope) {
console.log('scope', scope.val) // SHOWS UNDEFINED BUT INSERT DATA IN TEMPLATE
if(scope.val) scope.val = scope.val.replace(/\d/g,'')
}
}
})
.directive('two', function(){
return {
restrict: 'E',
scope: {
val:'='
},
template: '<div> 2222 {{val}} </div>' ,
link: function (scope) {
console.log('scope', scope.val)
scope.val = scope.val.replace(/\d/g,'')
}
}
});
&#13;
示例:JsFiddle
答案 0 :(得分:2)
您只需要使用attr.$observe
从单向绑定访问值,将链接功能的代码更改为 -
link: function (scope,elum,attr) {
attr.$observe('val', function(value) { console.log('scope', scope.val) })
//console.log('scope', scope.val)
if(scope.val) scope.val = scope.val.replace(/\d/g,'')
}
查找更新JsFiddle