Is there a way to link a function for ng-click in an Angular directive?
I have defined my click handler within the link function, but using it with ng-click in the directive does not trigger it.
For example:
In an Angular directive called "card", I aim to change its flipped attribute from false to true when clicked.
Controller - contains an array of cards:
$scope.cards = [
{id: 23, flipped: false},
{id: 315, flipped: false},
{id: 182, flipped: false}
];
Directive - renders a card and includes a flip function:
myApp.directive('card', function(){
return {
scope: {
card: "="
},
link: function(scope, elem, attrs) {
// Function to flip the card on click via ng-click.
scope.flipCard = function(){
console.log('flipped!');
scope.card.flipped = true;
}
},
template: "<div>I'm a card</div>"
}
});
HTML - displays all the cards:
<div ng-repeat="card in cards">
<card card="card" ng-click="flipCard()"></card>
</div>
The flipCard() function is not getting called when a card is clicked. What could be causing this issue?
Important Note:
I am familiar with using bind to attach handlers in the link function. My question revolves around why ng-click appears unable to access the scope of the directive as established in the link function. While a solution with bind works, I am seeking an alternative that functions 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;
};
}