nourdine
nourdine

Reputation: 7597

How do you pass in data to custom directives as a value of the attribute itself?

I have a directive defined as such:

angular.module("main.directives").directive("todo", function() {

   return {
      restrict: "A",
      scope: {
         todo: "=entity"
      },
      replace: false,
      templateUrl: "todo.html",
      link: function(scope, element, attributes) {       
      }
   };
});

which I use like this from templates:

<div todo entity="todoData"></div>

todoData comes from a controller or some other the local scope. Anyway it all works like a charm, so that's cool!

My question is the following: How do I have to modify the directive definition so that it also works with a markup of this type:

<div todo="todoData"></div>

As you can see the data is now passed in as the value of the attribute marking the directive. Just like ng- directives do:

<p ng-repeat="bit in data"></p>
<p ng-click="whatever()"></p> 

How can that be achieved?

Thanks

Upvotes: 0

Views: 2567

Answers (3)

Bilal Ahmed Yaseen
Bilal Ahmed Yaseen

Reputation: 2654

When you write an attribute directive in angularjs you might want to have it fed by an attribute value. For example, something like this:

<div my-attribute="somevalue"></div>

How then do you create a new scope that takes that in? It's not obvious. Any here's how you do it:

app.directive('myAttribute', function() {
    return {
        restrict: 'A',
        scope: {
            myAttribute: '='
        },
        template: '<div style="font-weight:bold">{{ myAttribute | number:2}}</div>'
    };
});

The trick to notice is that the "self attribute" because of the name of the attribute in camel case.

Here is the Reference to This Answer!

Upvotes: 1

chfumero
chfumero

Reputation: 1147

you must eval the value of the attribute inself. The isolate scope is not one of my favorites kind of scopes for a directive. Instead you can use, scope = true, to inherit from the parent controller. This will allow you to use all the variable exposes on the parents scopes.

in your case.

angular.module("main.directives").directive("todo", function() {

   return {
      restrict: "A",
      scope: true,
      replace: false,
      templateUrl: "todo.html",
      link: function(scope, element, attributes) {   

           scope.todo = scope.$eval(attributes[todo]);

      }
   };
});

now your todo directive could be used. Like any other ng- directive.

example:

<div todo="getTodoList()"></div>
<div todo="[{description:'hahahha'}]"></div>

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691715

Replace

scope: {
    todo: "=entity"
},

by

scope: {
    todo: "=todo"
},

or simply

scope: {
    todo: "="
},

Upvotes: 2

Related Questions