apelidoko
apelidoko

Reputation: 790

AngularJS get Directive properties and pass as a paremeter on binded Click Event

I'm new to angularjs and I want to know how can I get directives properties and pass it as a parameters on my Directive's click event,

here is my HTML Directive, the <a> tag together with its properties is dynamically created. The properties I want to get and pass as parameters are the id and status

<a href='#' class='article-link' id='"+b.id+"' status='"+articleStatus+"' display-article-div-directive>

here is my Angular Directive

myApp.directive("displayArticleDivDirective", function($parse,$rootScope)   {

        return function($scope, $element, $attrs) {

            var id =  $parse($attrs.id)($scope);
            var status =  $parse($attrs.status)($scope);
            var clickingCallback = function(id,status) {

                console.log('stat: '+status);
                /* status and id is undefined here */
            };
            $element.bind('click', clickingCallback);
        }
    });

I hope you can paste here a working sample, thank you very much,

Upvotes: 0

Views: 33

Answers (1)

Claies
Claies

Reputation: 22323

Use a scope on your directive to enable the data to be passed in, instead of parsing the element. Something like this:

app.directive("displayArticleDivDirective", function() {
  return {
    scope: {
      id: "=",
      status: "="
    },
    link: function(scope, element, attrs) {
      var clickingCallback = function() {
        console.log('stat: ' + scope.status);
        console.log('id: ' + scope.id);
      };
      element.bind('click', clickingCallback);
    }
  };
});

HTML:

<a href='#' class='article-link' id='"+b.id+"' status='"+articleStatus+"' display-article-div-directive>Test </a>

http://plnkr.co/edit/PLBQeQkLelbm9nHnBHIt?p=preview

Upvotes: 1

Related Questions