简体   繁体   中英

Define a function for ng-click in an Angular directive

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;
  }; 
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM