我正在尝试使用自定义指令中的单向绑定进行一些数据操作,但我第一次收到“未定义”.我应该怎么做指令而不是使用$watch?
例:
<one val={{arr[1].value}}> </one>
<two val="arr[0].value"> </two>
指令:
.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,'')
}
}
});
示例:JsFiddle
最佳答案 您只需要使用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