Umakanta Behera Umakanta Behera - 10 days ago 5
AngularJS Question

Triggering click event on first element of a list using Angular

I want to trigger click on first li of a List.I am using ng-repeat to populate the List.I know it can be done using a directive but not sure how to do it.

HTML:

<ul id="my-ul" click-first-row>
<li ng-repeat="row in rows" ng-click="getRow(row,$index)" >{{row.requestId}}</li>
</ul>


JS:

angular.module('App',[]).controller('Ctr',function($scope){
$scope.rows = res.inboxNewRecords;
angular.element(document.querySelector('#my-ul li')).triggerHandler('click');
$scope.getRow = function(data,index){
$scope.newReq = data;
};
}).directive('clickFirstRow',function(){
return{
restrict:'A',
link:function(scope,el,attr){
console.log(el[0]);
el[0].find('li').triggerHandler('click')
}
};
});


Please find the plunker for the same.

Answer

A couple of things with your code:

  1. "el[0]" will return a native element that won't support the .find() selector. You want to find the first <li> and wrap it with angular.element so you can call triggerHandler() on it.

  2. This code will fire too early, the click handler won't be properly bound before you trigger the click. You could wrap it in a $timeout(), or better still use the $$postDigest callback.

Working plunkr: https://plnkr.co/edit/O6BeOEieSdNj3Y3KkAYc?p=preview

scope.$$postDigest(function() {
    var firstRow = el.find('li')[0];
    angular.element(firstRow).triggerHandler('click');
});
Comments