Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 <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?

like image 967
Naor Avatar asked Apr 16 '14 13:04

Naor


People also ask

Which directive is used to specify the URL for a element?

templateUrl can also be a function which returns the URL of an HTML template to be loaded and used for the directive. AngularJS will call the templateUrl function with two parameters: the element that the directive was called on, and an attr object associated with that element.

What is custom directive in AngularJS?

What is Custom Directive? A Custom Directive in AngularJS is a user-defined directive that provides users to use desired functions to extend HTML functionality. It can be defined by using the “directive” function, and it replaces the element for which it is used.

What is $compile in AngularJS?

Overview. Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together. The compilation is a process of walking the DOM tree and matching DOM elements to directives. Note: This document is an in-depth reference of all directive options.

Which type of directives starts with * ng?

AngularJS directives are extended HTML attributes with the prefix ng- . The ng-app directive initializes an AngularJS application.


1 Answers

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.

like image 88
EnigmaRM Avatar answered Oct 10 '22 17:10

EnigmaRM