Reputation: 2555
I have the following code and I want to get the value of myevent attribute, I try to get it by :attr.myevent but it returns 'undefined'
myApp.directive('eventCustom' , function(){
return{
restrict: 'AEC',
template: '<button myevent="click">clickme</button>',
link: function(scope, elem , attr){
elem.bind('click' , function(){
alert(attr.myevent);
});
}
}
})
http://jsfiddle.net/HB7LU/19711/
Upvotes: 0
Views: 1043
Reputation: 11596
If you use the following you can get it.
elem.bind('click' , function(){
alert(elem[0].childNodes[0].textContent);
});
Upvotes: 0
Reputation: 1376
You can like this
myApp.directive('eventCustom' , function(){
return{
restrict: 'AEC',
template: '<button myevent="click">clickme</button>',
link: function(scope, elem , attr){
elem.bind('click' , function(){
alert(attr.$$element.find('button').attr('myevent'));
});
}
}
})
Upvotes: 0
Reputation: 5873
The approach you are using will detect the values of attributes on the <event-custom>
element, not attributes on elements inside the directive's template.
For example if you use this HTML, you will get the result "test".
<event-custom myevent='test'></event-custom>
In order to get the value of myevent
on the button you could can access it from the click event, but it's not the ideal way to do it. Angular lets you avoid dealing with the DOM and you may have to do it occasionally but I doubt it's necessary in this case.
link: function(scope, elem , attr){
elem.bind('click' , function(event){
alert(event.target.getAttribute("myevent"));
});
}
Typically if you want to detect click events within the template and pick them up in the directive you can use a controller e.g.
myApp.directive('eventCustom' , function(){
return{
restrict: 'AEC',
template: '<button ng-click="clickme(\'test\')">clickme</button>',
link: function(scope, elem , attr){
},
controller: function($scope){
$scope.clickme = function(value){alert(value)};
}
}
})
Upvotes: 3