简体   繁体   English

在AngularJS中,您可以在使用ng-repeat时自动从生成的对象中绑定onclick函数吗?

[英]In AngularJS can you automatically bind an onclick function from the object you're generating when using ng-repeat?

I have an array of items and Im using ng-repeat to create an element for each item in the array. 我有一个项目数组,我使用ng-repeat为数组中的每个项目创建一个元素。 One of the attributes on each item could possibly be a function, like this: 每个项目的属性之一可能是一个函数,如下所示:

item.myFunction = function(){
// do something
}

Can I bind this to an element using an onclick or ng-click or something? 我可以使用onclick或ng-click或其他方法将其绑定到元素吗? I have tried the following: 我尝试了以下方法:

<p onclick="{{item.myFunction}}">click me</p>

<p ng-click="{{item.myFunction}}">click me</p>

<p ng-attr-onclick="{{item.myFunction}}">click me</p>

Am I trying to achieve something that isn't possible? 我是否在试图实现不可能的目标? Can't find any help on google. 在Google上找不到任何帮助。

I don't know if this possible, but you could try implementing a wrapper function that will call your specific object function: 我不知道这是否可行,但是您可以尝试实现一个包装函数,该包装函数将调用您的特定对象函数:

<p ng-click="{{myFunction(item)}}">click me</p>

Then implement the function like this in your controller: 然后在您的控制器中实现如下功能:

myFunction(item){ item.myFunction() }

You can pass the object to the click function and do the same, 您可以将对象传递给click函数并执行相同的操作,

Controller: 控制器:

$scope.myFunction = function(someObject){
// do something
}

HTML 的HTML

<p ng-click="{{myFunction(item)}}">click me</p>

Working SampleApp 工作SampleApp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM