将当前的HTMLElement传递给ng-click

时间:2014-03-12 12:55:39

标签: javascript angularjs

是否可以将HTMLElement传递给控制器​​上配置的ng-click?

以下是一些示例代码:

<div ng-controller="Controller">
   <ul ng-repeat="item in items">
      <li ng-click="handleThisElement($element)" id="{{item.id}}" >{{item.name}}</li>
   </ul>
</div>

控制器:

function ($scope) {
  $scope.items = [
    {name: 'Bilbo', id='Bilbo'},
    {name, 'Frodo', id='Frodo'},
    {name: 'Pippin', id='Pippin'},
    {name: 'Merry', id='Merry'},
    {name: 'Sam', id='Sam'}
  ];

  $scope.handleThisElement = function (element) {
     alert(element.id); // should alert (Bilbo || Frodo || Pippin || Merry || Sam)
  }

更新

不要混淆,我说我想让整个元素不仅仅是模型中的id。

$ event.target - 在某些版本的IE中不起作用。

4 个答案:

答案 0 :(得分:14)

HTML:

<div ng-controller="Controller">
   <ul ng-repeat="item in items">
      <li ng-click="handleThisElement($event)" id="{{item.id}}" >{{item.name}}</li>
   </ul>
</div>

和js:

function ($scope) {
  $scope.items = [
    {name: 'Bilbo', id='Bilbo'},
    {name, 'Frodo', id='Frodo'},
    {name: 'Pippin', id='Pippin'},
    {name: 'Merry', id='Merry'},
    {name: 'Sam', id='Sam'}
  ];

  $scope.handleThisElement = function ($event) {
     alert($event.target.id);
  }

答案 1 :(得分:0)

handleThisElement(item);

以下是plunker

http://plnkr.co/edit/Hv6DwKMRbYlQ43m8UQkU?p=preview

答案 2 :(得分:0)

将<{1}}用于此

$watch

答案 3 :(得分:-1)

尝试

<div ng-controller="Controller">
   <ul ng-repeat="item in items">
     <li ng-click="handleThisElement(item)" id="{{item.id}}" >{{item.name}}</li>
   </ul>
</div>

function ($scope) {
   $scope.items = [
     {name : 'Bilbo', id:'Bilbo'},
     {name : 'Frodo', id:'Frodo'},
     {name : 'Pippin', id:'Pippin'},
     {name : 'Merry', id:'Merry'},
     {name : 'Sam', id:'Sam'}
   ];

   $scope.handleThisElement = function (element) {
    alert(element.id); // should alert (Bilbo || Frodo || Pippin || Merry || Sam)
   }
}