简体   繁体   中英

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. 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? 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.

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,

Controller:

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

HTML

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

Working SampleApp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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