4

I am trying to get the attributes of "abc" defined as custom directive in angularjs:

<div abc="user">
    Access granted!
</div>

and then change the text inside div using custom directive:

.directive('abc', function() {
  var attr;
  return {
    link: function (scope, element, attributes) {
      attr = attributes.abc;
      console.log(attr);
    },
    template: "" + attr
  };
});

The result should be 'user' but it is undefined as attr is not defined at the time template is executed. So, any possible help how to tackle this issue?

3 Answers 3

5

You can't edit the template using a dynamic loaded from the attribute, you have to use the scope in order to update your template

template: '<div> {{abc}} </div>', // here it's scope.abc
link : function (scope, elem, attr) {
    scope.abc = attr.abc;
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks! and what to do for not returning any template depending on the logic of my function, so that the original "Access granted" can be visible?
That's really an amazing way to do it. Helped me solve my issue. Thanks a ton! BTW, could there be any other way to do it without having to assign it to the scope?
1

You have to extend your scope and add your attribute 'attr' in your scope

scope: {
   attr: '=abc'
}

and then from html you can define your attribute like so

<div abc attr="user">
    Access granted!
</div>

3 Comments

here the console is showing 'attr' is not defined!!
I did a mistake try this one scope
try console.log(scope)
1

You can do it like that:

.directive('abc', function() {

  return {
    scope: {
       attr: '=abc'
    },
    link: function (scope) {
      console.log(scope.attr);
    },
    template: "" + attr
  };
});

3 Comments

here the console is showing 'attr' is not defined!!
may try scope.attr
Thanks, I forgot that

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.