Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get attribute value in template in angularjs custom directive?

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?

like image 676
root Avatar asked Mar 15 '23 23:03

root


2 Answers

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;
}
like image 121
Mathieu Bertin Avatar answered Apr 25 '23 21:04

Mathieu Bertin


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>
like image 35
Ismapro Avatar answered Apr 25 '23 21:04

Ismapro