2016-12-10 86 views
0

我想知道,如何将参数传递给AngularJS模板内部的动态函数。 我在桌上有很多行,每一行都有一个按钮添加存款。我想将行号传递给此按钮的ng-click函数。将参数传递给AngularJS模板内部的函数

这里是我的模板的片段:

<div id="documentsTable" class="table-responsive"> 
<table class="table"> 
    <thead> 
     ... 
    </thead> 
    <tbody ng-repeat="document in data"> 
     <tr> 
      ... 
      <td> 
       ... 
       <button ng-show="document.depositCheckbox" ng-click="addDeposit({id: document.number})" id="addDepositBtn" 
         type="submit" class="btn btn-primary">Add deposit</button> 
      </td> 
     </tr> 
    </tbody> 
</table> 

指令:

.directive('documentDirective', ['$compile', '$templateCache', function() { 
return { 
    templateUrl: 'templates/documentTemplate.html', 
    scope: { 
     data: '=', 
     addDeposit: '&' 
    }, 
    restrict: 'E' 
}}]); 

而在我的HTML文件我有:在

<document-directive data="documents" add-deposit="addDeposit()"></document-directive> 

功能addDeposit我调节器:

$scope.addDeposit = function(documentId) { 
    for(var i=0; i<$scope.documents.length; i++) { 
     if($scope.documents[i].number == documentId) { 
      var depositLength = $scope.documents[i].deposit.length; 
      var deposit = {'number': depositLength, 'value': 0, 'paymentDate': new Date(), 'firstRow': false}; 
      $scope.documents[i].deposit.push(deposit); 
      break; 
     } 
    } 
} 

谢谢!

回答

2

好吧,据我了解,你试图得到哪一行,你得到的请求?

我想你应该可以用ng-changed的$index属性来做到这一点。

因此,像:

<button ng-show="document.depositCheckbox" ng-click="addDeposit({id: document.number, rowNumber: $index})" id="addDepositBtn" 
         type="submit" class="btn btn-primary">Add deposit</button> 

编辑: 试试这个,然后:

<button ng-show="document.depositCheckbox" ng-click="addDeposit()(document.number)" id="addDepositBtn" type="submit" class="btn btn-primary"> Add deposit</button> 

你在哪里传递函数:

<document-directive data="documents" add-deposit="addDeposit"></document-directive> 

的方法传递的参数: https://stackoverflow.com/a/26244600/1958344

+0

它不能解决我的问题,因为我的** id:document.number **存储rowNumber。问题是,在我的addDeposit函数中我无法获得这个值 - 它是未定义的。 – piotrb

+0

它看起来像: 我在我的HTML元素声明,该函数addDeposit()没有参数,所以当我在我的模板中使用它时,我不能传递任何参数到这个函数。 – piotrb

+0

不应该与它有任何关系,因为你不必在那里声明变量。你可以发布一些控制器代码,你在哪里定义'addDeposit'函数? –