如何在带有隔离范围的指令中使用ng-click

时间:2015-12-01 00:36:35

标签: javascript angularjs

我试图在具有隔离范围的自定义指令内使用ng-click调用函数。我不知道怎么做,因为它不起作用。

控制器:

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

指令js:

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

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


 }

});

指令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>

1 个答案:

答案 0 :(得分:1)

问题是您没有将该属性添加到指令实例。

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

然后通过传递一个对象来调用带有id参数的函数:

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

另一种方法是传递函数对象本身:

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

然后在调用原始函数之前调用eventBookmark()来检索该函数:

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