I'm new to angularjs and I don't know if this is possible and if possible how to implement it. I want to create a custom directive with a controller that uses information passed to it through attributes. This is a non working example of what I want to implement:
The HTML should look like:
<div ng-app="test">
<custom-directive attr1="value1" attr2="value2"></custom-directive>
</div>
And the js:
var app = angular.module('test', [ ]);
app.directive("customDirective", function(){
return {
restrict: 'E',
scope: ???,
controller: function(){
console.log("print attributes value: " + attr1 + ", " + attr2 );
}
}
};
});
And the expect console output should be:
print attributes value: value1, value2
Any idea? Thanks!
Custom directives are used in AngularJS to extend the functionality of HTML. Custom directives are defined using "directive" function. A custom directive simply replaces the element for which it is activated.
AngularJS allows you to create custom directives with which it becomes easier to encapsulate and simplify DOM manipulation in AngularJS. These directives extend the HTML functionality.
Angular has three kinds of directives. Components - is a directive with a template. Structural directives - controls the DOM elements, using which we can add or remove elements from DOM. For ex: *ngIf, *ngFor etc. Attribute directives - to change the behavior or apperance of an element, component or the directive.
Steps to create a custom attribute directiveCreate a class decorated with @Directive. Assign the attribute directive name to the selector metadata of @Directive decorator. Use ElementRef class to access DOM to change host element appearance and behavior.
In your directive you can define the scope objects (attributes) you want to access and use as follows:
app.directive("customDirective", function(){
return {
restrict: 'E',
scope: {attr1: "=", attr2: "="},
link: function(scope, elem, attr){
console.log("print attributes value: " + attr.attr1 + ", " + attr.attr2 );
}
};
There are different types of bindings you can use:
See below link for more information: http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-2-isolate-scope
Looking further I found this possible solution to my problem. It is very similar to the one proposed by Plunker with only slight changes in the syntax. This one works for me but I do not understand why the proposed by Plunker not.
app.directive('customDirective', function(){
return {
compile: function() {
return {
pre: function(scope, element, attributes) {
console.log("Value: " + attributes.attr1 + attributes.attr2);
}
};
}
}
});
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