Andre Mendes
Andre Mendes

Reputation: 7677

how to use ng-click in directive with isolated scope

Im trying to call a function with ng-click inside a custom directive with isolated scope. Im not sure how to do it because its not working.

Controller:

//Add event to users bookmark
$scope.addEventBookmark = function(id) {
    console.log(id);
};

Directive js:

//Event Card
app.directive('eventCard', function(){
return{
    restrict: 'E',
    templateUrl: 'app/directives/html/eventcard.html',
    replace: true,
    scope: {

        eventObject: '=',
        getHashes: "&",
        eventBookmark: "&addEventBookmark"
    }


 }

});

Directive html

<div class="col-md-4">
<div class="event-img-area">
    <a ng-href="#/event/{{ eventObject.id }}">
        <img src="images/event-img-pholder.png">
    </a>
</div>
<div class="event-short-info-area">
    <p class="event-time-card">{{ eventObject.datetime }}<br>
    <span class="event-title-card">{{ eventObject.title }}</span></p><br>
    <span class="event-address-card">
        {{ eventObject.address.road }}, {{ eventObject.address.city }}, {{ eventObject.address.state }}, {{ eventObject.address.postal }}, {{ eventObject.address.country }}
    </span>
</div>
<div class="event-tags-area clearfix">
    <div class="hash-card">
        <span id="insertHashes" class="hashes">
            {{ getHashes({ data: eventObject.hashes }) }}
        </span></div>
    <div class="bookmark-card">
        <a href ng-click="eventBookmark(1)"><i class="fa fa-bookmark-o"></i></a>
    </div>
</div>

<event-card event-object="event" get-hashes="getAllHashes(data)"></event-card>

Upvotes: 0

Views: 100

Answers (1)

HankScorpio
HankScorpio

Reputation: 3651

The problem is you haven't added that attribute to your directive instance.

<event-card event-object="event" get-hashes="getAllHashes(data)" add-event-bookmark="addEventBookmark(id)"></event-card>

Then call the function with the id parameter by passing an object:

<a href ng-click="eventBookmark({id: 1})"><i class="fa fa-bookmark-o"></i></a>

Another way is to pass in the function object itself:

<event-card event-object="event" get-hashes="getAllHashes(data)" add-event-bookmark="addEventBookmark"></event-card>

And then retrieve that function by calling eventBookmark() before calling the original function like this:

<a href ng-click="eventBookmark()(1)"><i class="fa fa-bookmark-o"></i></a>

Upvotes: 1

Related Questions