2014-07-21 31 views
4

我需要將一個特定元素的$ index值與ng-repeat一起添加到javascript函數中。 我的代碼示例:ng-repeat將索引值傳遞給一個函數

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

現在我加入了幾個按鈕,當按下特定的按鈕,我需要把它的具體$指數的doStuff($指數)功能。 有什麼想法?

+0

哼哼......什麼?!什麼不適用於你當前的代碼? – Blackhole

+0

有什麼問題? – Shomz

+0

問題是,當我按下按鈕它甚至不去函數,並且不要傳遞$索引。 – KBE

回答

1

您需要確保在使用ng-click時,調用的函數是在控制器的作用域中聲明的。

因此,如果你的函數名稱爲doStuff(指數),你應該可以看到這個地方定義你的代碼(以下使得假設你的模塊和控制器名稱):

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

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

} 
7

請看這裏: 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'}]; 
}); 
4

這裏是一個例子。

http://jsfiddle.net/bdmRs/

你有什麼有看起來不錯,但你可能會丟失與doStuff函數定義的東西。它必須定義在這樣的$範圍內:

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