0

I am creating a directive in angularJS which will replace the element. I have a variable in parent scope which is bind to the element.

I want to update the directive scope variable on change the parent scope variable value.

The element is like below

<my-element attr-xyz="scope_variable"></myelement>

When I write the directive as below it give the updated value whenever scope variable update

.directive('myElement', function(){
    return function(scope, elem, attr){
        scope.$watch(attr.attrXyz, function(value) {
            console.log(value);
        });
    }
});

but when I write the same code like below it give the undefined value

return {
    scope: {attrXyz: '@'},
    restrict: 'E',
    replace: true,
    link: function(scope, element, attr, controller){
        scope.$watch(attr.attrXyz, function(value){
            console.log('value = '+value);
        });
    }
}
1
  • A better way is to replace link: function with controller:function Commented Sep 9, 2015 at 13:58

2 Answers 2

2

Both way works. (Directive 1-2) http://plnkr.co/edit/2kJT1mkaORsS8RUOyZ0N?p=preview

However, if u introduce isoloated scope - 2nd way do not work. (Directive 3)

Then you can use $observe (Directive 4)

  attr.$observe('attrXyz', function(value){
      console.log('4: '+ value);
  });

Or you can define it in scope and use watch.

Sign up to request clarification or add additional context in comments.

3 Comments

I have defined it in scope as scope:{attrXyz:'@'} and used watch but it was not working. I have replaced it with attr.$observe('attrXyz',function(value){}); now its working fine for me.
added to plunk directive5 with scope:{attrXyz:'@'} and watch
Okay, basically the changes of attr.attrXyz to attrXyz only. Thanks a log.
0

I recommend you to use only ng-attr

<my-element ng-attr-xyz="scope_variable"></myelement>

Only use $observe and $watch if you really need to trigger a function/validation in the directive when this value changes, otherwise you are adding listener just for that and is more maintainable to use the attribute in the template.

3 Comments

Is ng-attr deprecated? I can't find it in the documentation
Seems to be deprecated, after version 1.3.20. Here is the doc.
The functionality is still working, but reading on the migration docs seems to be no longer needed in angular 1.5. Correct me if i'm wrong

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.