在自定义指令中将参数传递给 ng-click 指令 [英] Passing parameter to ng-click directive, within custom directive

查看:20
本文介绍了在自定义指令中将参数传递给 ng-click 指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using ng-repeat in the template for a custom directive as follows:

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

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

When rendered on the page the source looks like

<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}} 参数,它可以工作并调用该函数.使用索引,它不会触发.

I have the function togglePhoto defined in my directive. Without the {{index}} parameter being passed in it works and the function is called. With the index, it doesn't fire.

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

How do I get the index of the photo clicked into the togglePhoto function?

推荐答案

解决了这个问题.希望它可以帮助其他人坚持下去.

Figured this out. Hope it helps anyone else stuck on it.

首先是这个

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

应该

ng-click="togglePhoto($index)"

不需要大括号!

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

Secondly I found that you can pass the event object into the click function eg

ng-click="togglePhoto($event)"

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

Then catch that event and find out what element trigged it in your click function

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

这篇关于在自定义指令中将参数传递给 ng-click 指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆