How to get the value of an attribute in a template in an angularjs custom directive?
I'm trying to get the "abc" attributes defined as a custom directive in angularjs:
<div abc="user">
Access granted!
</div>
and then change the text inside the div with a special 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 undefined because attr was not set when the template was executed. So, any possible help for solving this problem?
+3
root
source
to share
3 answers
You cannot edit the template using dynamic loading from attribute, you need to use scope to update your template
template: '<div> {{abc}} </div>', // here it scope.abc
link : function (scope, elem, attr) {
scope.abc = attr.abc;
}
+3
Mathieu Bertin
source
to share
You can do it like this:
.directive('abc', function() {
return {
scope: {
attr: '=abc'
},
link: function (scope) {
console.log(scope.attr);
},
template: "" + attr
};
});
+1
xavier hans
source
to share
You have to expand your scope and add your attr attribute in your scope
scope: {
attr: '=abc'
}
and then from html you can define your attribute like so:
<div abc attr="user">
Access granted!
</div>
+1
Ismapro
source
to share