如何使用AngularJS获取ng-repeat
内单击元素的上一个元素?在jquery中,可以使用$(this).prev()
或类似的东西来完成。
对于一个例子,我有这个:
<table class="table table-striped" ng-controller="UserController as vm">
<tr ng-repeat="(key, value) in vm.users">
<td>{{value.username}}</td>
<td><button name="btnDelete" id="btnDelete" class="btn btn-danger" ng-click="vm.delete(key)">Delete</button></td>
</tr>
</table>
然后在我的UserController
:
function UserController() {
var vm = this;
vm.delete = function(buttonId) {
// get the clicked element and get previous element
// "this" doesn't work as it returns the vm itself
}
}
提前致谢!
更新
应该返回<td>
vm.username
元素
答案 0 :(得分:3)
试试这个
ng-click="vm.delete(key,$index)"
,您的控制器代码应为
function UserController() {
var vm = this;
vm.delete = function(buttonId,index) {
if(index > 0){
var result = vm.users[index-1].username
}
}
}