Angularjs custom directive with custom attributes

I am 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 the information passed to it through attributes. This is a broken example of what I want to implement:

HTML should look like this:

<div ng-app="test"> <custom-directive attr1="value1" attr2="value2"></custom-directive> </div> 

And 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 expected console output should be:

print attribute value: value1, value2

Any idea? Thanks!

+7
javascript angularjs angularjs-scope angularjs-directive
source share
3 answers

In your directive, you can define the area objects (objects) that you want to access and use them 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 various types of bindings you can use:

  • = for two-way binding
  • @ just reads the value (one way binding)
  • & used to bind functions

See the link below for more information: http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-2-isolate-scope

+4
source share

In the future, I found this possible solution to my problem. It is very similar to the one proposed by Plunker with minor syntax changes. This works for me, but I don’t understand why the one proposed by Plunker was not.

 app.directive('customDirective', function(){ return { compile: function() { return { pre: function(scope, element, attributes) { console.log("Value: " + attributes.attr1 + attributes.attr2); } }; } } }); 
+2
source share

Directives can become quite complex. Knowing your ultimate goal would allow a better answer, but this is the easiest way to do what you ask for:

 var app = angular.module('test', []); app.directive("customDirective", function(){ return { link: function(scope, el, attr){ console.log("print attributes value: " + attr.attr1 + ", " + attr.attr2 ); } } }); 

Plunker

0
source share

All Articles