如何在AngularJS中获取组件的ID?
HTML
<li class="list-group-item" id="person_2" ng-click="invitePerson(this)">
<span class="label label-primary">A</span> Alexandre Dolabella Resende
</li>
JS
$scope.invitePerson = function(id) {
alert(id);
};
警报返回[对象对象],如何访问我的组件ID? (在我的情况下,应该是person_2)
CONSOLE.LOG
答案 0 :(得分:2)
使用$ event获取eventhandler参数。从那个参数我们可以得到目标元素及其属性
<li class="list-group-item" id="person_2" ng-click="invitePerson($event)">
<span class="label label-primary">A</span> Alexandre Dolabella Resende
$scope.invitePerson = function(e){
alert(e.target.id);
}
答案 1 :(得分:0)
您可以使用ng-init或控制器初始化值。然后定义一个模型,然后您可以将该模型传递给控制器函数,例如invitePerson
工作Plunker
HTML:
<ul>
<li class="list-group-item" id="person_2"
ng-init="person_2=5"
ng-model="person_2"
ng-click="invitePerson(person_2)">
<span class="label label-primary">A</span> Alexandre Dolabella Resende
</li>
</ul>
JS:
app.controller('MainCtrl', function($scope) {
$scope.invitePerson = function(id){
alert(id);
}
答案 2 :(得分:0)
当我看到“person_2”时,我会立即想到ng-repeat,如果你想在你的部分http://plnkr.co/edit/b6ZePD826FauaY9x8b9p?p=preview
中迭代对象,也许你也应该这样做<label for="list">List</label>
<ul id="list">
<li class="list-group-item" id="person{{$index}}" ng-click="invitePerson(person)" ng-repeat="person in persons">
<span class="label label-primary">{{person.label}}</span> {{person.name}}
</li>
</ul>
<label for="invited">Invited</label>
<ul id="invited">
<li ng-repeat="invite in invited track by $index">{{invite.name}}</li>
</ul>