Naor Naor - 17 days ago 6
AngularJS Question

AngularJS Directive for specific tag name

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

tags. If the user put this directive on a
, I don't want the directive to be active. How can I do that?


You have 2 options.

#1 Use your existing directive that you have working and add a couple lines


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) {



<myIMG path=''></myIMG>

I personally like option 2 best. But I know that can be more daunting, and often introduces other unexpected things.