0

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?

rsijaya
  • 159
  • 2
  • 14

2 Answers2

1

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

bmleite
  • 26,850
  • 4
  • 71
  • 46
  • hi bmleite, i have update fiddle http://jsfiddle.net/Jx4hm/1/ How i bind value func to set value for scope.func2 outside the observe? thx anyway – rsijaya Jan 21 '13 at 14:35
  • I don't know if I understood it correctly, but please check if this fiddle helps: http://jsfiddle.net/bmleite/Jx4hm/2/ – bmleite Jan 21 '13 at 15:05
  • thanks for help, i use $watch to multiple value http://stackoverflow.com/questions/11952579/watch-multiple-things-in-angularjs – rsijaya Jan 22 '13 at 02:19
0

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.)

Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
  • ok thanks for your info, i use $watch to multiple value http://stackoverflow.com/questions/11952579/watch-multiple-things-in-angularjs – rsijaya Jan 22 '13 at 02:19