0

How can I attach a function to be used with ng-click in an Angular directive?

I have defined my click handler in the link function. Using this function in my directive's ng-click attribute does not run it.

Example:

I have an angular directive called "card". When "card" is clicked, I want to change its flipped attribute from false to true.

controller - has an array of cards

$scope.cards = [
  {id: 23, flipped: false},
  {id: 315, flipped: false},
  {id: 182, flipped: false}
];

directive - renders a card, and has a function to "flip" it.

myApp.directive('card', function(){
  return {
    scope: {
      card: "="
    },
    link: function(scope, elem, attrs) {
      // Create a function that will be called on click via ng-click.
      scope.flipCard = function(){
        console.log('fipped!');
        scope.card.flipped = true;
      }
    },
    template: "<div>I'm a card</div>"
  }
});

html - show all the cards

<div ng-repeat="card in cards">
  <card card="card" ng-click="flipCard()"></card>
</div>

When a card is clicked, the flipCard() function isn't being called. Why is this?

Note

I am aware of using bind to attach handlers in link. I am specifically asking why ng-click does not seem to have access to the directive's scope, as defined in link. Here is a solution that works with bind. I am looking for a solution that works with ng-click.

link: function(scope, elem, attrs) {
  elem.bind('click', function(e){
    scope.flipCard();
  });

  scope.flipCard = function(){
    console.log('tap!');
    scope.card.flipped = true;
  }; 
}
2
  • 1
    you need to use transclusion if you want to take HTML elements outside the directive and give them access to the scope inside the directive. Also, scope.flipped doesn't really make sense, because flipped is a property of the card, not a property of the directive.... Commented Mar 14, 2015 at 23:15
  • 1
    angular-tips.com/blog/2014/03/transclusion-and-scopes Commented Mar 14, 2015 at 23:18

1 Answer 1

1

The problem is that ng-click on your <card> element tries to call flipCard() from controller's scope, not directive's one.

I'd write something like this:

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.