如何在角度ng-repeat中触发处理程序?

时间:2016-06-06 11:01:08

标签: javascript jquery angularjs

我有一个带有2个点击处理程序的转发器(在图标和跨度上)。当我点击 span 时,我想触发图标。我只实现了选择并触发转发器中的第一个元素(在第一个li中)。我在转发器中选择当前单击的元素时遇到了问题。

Live demo

HTML

<ul class="tree-list"">
 <li ng-repeat="stuff">
   <i ng-click="stuff"></i>
   <div>
     <span ng-click="forceClickTheIconAbove"></span>
   </div>
 </li>
</ul>

JS

// works
el = angular.element('.tree-list li:first-child i:first-child');
// output: el = [i.tree-branch-head.glyphicon.glyphicon-triangle-top, i.tree-branch-head.glyphicon.glyphicon-triangle-top, prevObject: init[1], context: document, selector: ".tree-list li:first-child i:first-child"]
el.click();

// not working
el = angular.element(".tree-list li")[0].children[0];
// output: el = <i ng-click="doStuff()">
el.click();

1 个答案:

答案 0 :(得分:1)

我想我理解你的问题,所以我做了一个例子:http://jsfiddle.net/Lvc0u55v/5028/

您可以使用$index

跟踪点击的li
var myApp = angular.module('myApp', []);

function MyCtrl($scope) {    
  $scope.forceClickTheIconAbove = function(item) {
    var el = angular.element(".tree-list li")[item].children[0];
    console.log(el);
    // output: el = <i ng-click="doStuff()">
    el.click();
  }
}

在你的HTML中:

<ul class="tree-list" ng-repeat="s in stuff">
    <li>{{s.name}}
      <i class={{s.name}}>Icon</i>
      <div>
        <span ng-click="forceClickTheIconAbove($index)">Click here to trigger icon</span>
      </div>
    </li>
  </ul>