How to bind scope from attrs.$observe?
<test func="hohoho"></test>
app.directive('test', function(){
return {
restrict: 'E'
, scope: { parentFunc: '@func'}
, link: function(scope, element, attrs) {
var func = '';
attrs.$observe('func', function(val) {
func = val;
console.log(func);
})
console.log('end');
console.log(func);
console.log(scope.parentFunc);
});
}
};
});
when i run, it will print
end
undefined
undefined
(an empty string)
hohoho
why i get undefined when i print func and parentFunc?
I believe those undefined lines are being printed somewhere else on the code and not on the Directive.
Check this fiddle and look at the console output: http://jsfiddle.net/bmleite/Jx4hm/
You should get something like this (which is the expected output):
end
1
2 undefined
3 hohoho
How i bind value func to set value for scope.func2 outside the observe?
From the Directives page, under section "Attributes":
during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined.
Only in the $observe callback function will the value contain the interpolated value. You'll have to move the code that is "outside the observe" into the $observe callback function.
Or try @bmleite's Jx4hm/2 fiddle, where '=' is used instead of '@'. If you don't need interpolatation (e.g., you don't need to do something like func="Hello {{modelInstance}}"), you can use '=', which sets up two-way databinding, but the value is available in the linking function. ('@' sets up one-way databinding.)