AngularJS Directive for specific tag name
angularjs, angularjs-directive, javascript
Solution
You have 2 options.
#1 Use your existing directive that you have working and add a couple lines
code:
link: function(scope,element,attr) {
if (element[0].tagName== 'IMG') {
//do your stuff
} else {
// do nothing or something else
}
}
#2 Restrict your directive to be just an element (as shown in Fizer Khan's answer).
.directive('myIMG', function() {
return {
restrict: 'E',
templateUrl: 'img.html',//essentially has <img src=''>
template: "<img src='scope.path'>",//build out your image tag here which will replace the HTML the directive is on
transclude: true,
scope: {
path: '='
},
link: function(scope, element, attr) {
}
};
});
HTML
<myIMG path=''></myIMG>
I personally like option 2 best. But I know that can be more daunting, and often introduces other unexpected things.
Problem
How can I force specific tag for a directive in AngularJS? For example, I want to create a directive that will be applied only on `<img>` tags. If the user put this directive on a `<div>`, I don't want the directive to be active. How can I do that?