【问题标题】:Passing parameter to ng-click directive, within custom directive在自定义指令中将参数传递给 ng-click 指令
【发布时间】:2015-07-14 21:29:17
【问题描述】:

我在自定义指令的模板中使用ng-repeat,如下所示:

<li ng-repeat="image in images">
    <img ng-src="{{image.url}}" ng-click="togglePhoto({{$index}})">
</li>

当呈现在页面上时,源看起来像

<li ng-repeat="image in images" class="ng-scope">
    <img ng-src="http://example.com/example.jpg" ng-click="togglePhoto(1)" src="http://example.com/example.jpg">
</li>

我的指令中定义了函数togglePhoto。如果没有传递{{index}} 参数,它就可以工作并调用该函数。使用索引,它不会触发。

togglePhoto函数中如何获取点击照片的索引?

【问题讨论】:

  • togglePhoto(x) 是如何定义的?

标签: angularjs angularjs-directive


【解决方案1】:

想通了。希望它可以帮助其他人坚持下去。

首先是这个

ng-click="togglePhoto({{$index}})"

应该是

ng-click="togglePhoto($index)"

不需要大括号!

其次我发现你可以将事件对象传递给点击函数例如

ng-click="togglePhoto($event)"

然后捕获该事件并找出在您的点击函数中触发它的元素

$scope.togglePhoto = function(e)
{
    console.log(e.currentTarget)
}

【讨论】:

    【解决方案2】:

    我认为问题在于您在 ng-click 内使用了双花括号,而 angular 不喜欢这样。

    尝试将中继器更改为这个(注意 $index 周围没有花括号):

    <li ng-repeat="image in images">
        <img ng-src="{{image.url}}" ng-click="togglePhoto($index)">
    </li>
    

    我还整理了一个可以工作的 jsfiddle 来展示它的工作原理。

    http://jsfiddle.net/n02ms8s0/4/

    【讨论】: