ng-repeat passing index value to a function
Asked Answered
S

4

7

I need to pass a $index value of a specific element, added with ng-repeat, to a javascript function. My code sample:

<tr ng-repeat="cells in CouponsList.CellPhones">
<td><button  ng-click="doStuff($index+1)">{{cells.localVendorAddress}}</button></td>

Now I am adding several buttons and when a specific button is pressed I need to send it's specific $index to the doStuff($index) function. Any idea?

Suggestibility answered 21/7, 2014 at 19:40 Comment(4)
Hum… what?! What doesn't work with your current code?Baronage
The problem is that when I press the button it doesn't even go to the function, and do not pass the $index.Suggestibility
Add a plunker/jsfiddle showcasing the problem.Thingumajig
I'm guessing doStuff() is not on the scope.Azo
N
8

please see here : http://jsbin.com/yeweh/4/edit

<a href="" ng-repeat="s in students" ng-click="doit($index)">{{s.name}} - {{s.class}} </a>


var app = angular.module('app', []);



app.controller('firstCtrl', function($scope){

  $scope.doit= function(index){
    alert(index)

  }

  $scope.students = [
           {name: 'Aa_Student', class: 'A_Class'},
           {name: 'Ab_Student', class: 'A_Class'},
           {name: 'Ac_Student', class: 'B_Class'},
           {name: 'Ba_Student', class: 'B_Class'},
           {name: 'Bb_Student', class: 'C_Class'},
           {name: 'Bc_Student', class: 'C_Class'}];
});
Necker answered 21/7, 2014 at 20:23 Comment(0)
R
4

Here is an example.

http://jsfiddle.net/bdmRs/

What you have there looks ok but you might be missing something with the function definition for doStuff. It must be defined on the $scope like this:

$scope.doStuff = function(idx){
    alert(idx);
};
Radiolucent answered 21/7, 2014 at 20:31 Comment(0)
C
1

You need to make sure when you're using ng-click that the function that is called is declared on the scope in the controller.

Therefore, if your function name is doStuff(index), you should see this defined somewhere in your code as (the below makes assumptions about your module and controller names):

var app = angular.module("MyModule", []);
app.controller("MyController", function($scope){

    $scope.doStuff = function(index){
        ... 
    }

}
Centrifugal answered 21/7, 2014 at 20:22 Comment(0)
H
0

KBE,

it seems that your function doStuff is not declared in your JS file with $scope.doStuff. In term of using the $index the syntax looks correct

Hampden answered 24/6, 2020 at 18:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.