I'm trying to do some data manipulation using a one-way binding in my custom directive, but I receive "undefined" first time. What should I do with directive and not to use $watch ?
Example:
<one val={{arr[1].value}}> </one>
<two val="arr[0].value"> </two>
Directives:
.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,'')
}
}
});
Example: JsFiddle
You just need to use attr.$observe
to access the value from one way binding change the code for link function to-
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,'')
}
Find the update JsFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With