Reputation: 1220
In my AngularJS app, I have a shopping cart directive where I need to assign a unique id from the directives link method to the id
attribute whilst setting the value of the other attributes from the exposed controller.
Directive
.directive('ngcartAddtocart', ['ngCart', function(ngCart){
return {
restrict : 'E',
controller : 'CartController',
scope: {
id: '=',
name:'@',
price:'@',
data:'='
},
transclude: true,
link:function(scope, element, attrs){
var ID = (function () {
return '_' + Math.random().toString(36).substr(2, 9);
}())
attrs.id = ID;
}
}])
View
<ngcart-addtocart
id="" <!--THIS I WANT TO DYNAMICALLY ADD ID FROM DIRECTIVE -->
name="item.name" <!-- PROVIDED BY CONTROLLER -->
price="item.price" <!-- PROVIDED BY CONTROLLER -->
data="object.data" <!-- PROVIDED BY CONTROLLER -->
></ngcart-addtocart>
Question
What is the best way to dynamically add the ID to the directive from the directives link method?
Upvotes: 0
Views: 35
Reputation: 48968
Use element.attr("id",ID);
link:function(scope, element, attrs){
var ID = (function () {
return '_' + Math.random().toString(36).substr(2, 9);
}())
̶a̶t̶t̶r̶s̶.̶i̶d̶ ̶=̶ ̶I̶D̶;̶
element.attr("id",ID);
}
For more information, see
Upvotes: 1