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?
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? 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.
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.
AngularJS directives are extended HTML attributes with the prefix ng- . The ng-app directive initializes an AngularJS application.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With