Ng-repeat pass index value to function

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

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

Now I add a few buttons, and when a particular button is clicked, I need to send the specific index $ index to the doStuff ($ index) function. Any idea?

+4
source share
3 answers

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'}];
});
+7
source

Here is an example.

http://jsfiddle.net/bdmRs/

What you have there looks fine, but you can miss something by defining a function for doStuff. It should be defined in $ scope as follows:

$scope.doStuff = function(idx){
    alert(idx);
};
+4

You need to make sure that when using ng-click, the function that is being called is declared in a scope in the controller.

Therefore, if your function name is doStuff (index), you should see it somewhere in your code as (below are the assumptions about the name of your module and controller):

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

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

}
+1
source

All Articles