Android Noob
Android Noob

Reputation: 3341

Angularjs - is there a way to programatically click on an HTML <select> element?

I've seen a javascript solution that goes a little something like this:

var select = document.getElementById('selectId')
select.click();

Is there an AngularJS approach/best practice to the same thing? (Off the top of my head, you'd wrap the above code in an ng-click)

Upvotes: 4

Views: 1613

Answers (2)

Shaunak
Shaunak

Reputation: 18028

Yes there is. Here's the angular equivalent of what you have in JavaScript

angular.element('#selectId').trigger('click');

Working example

Upvotes: 4

byrdr
byrdr

Reputation: 5487

Any DOM manipulation in angular should occur inside of a directive.

View

<div id="selectId" clickMe>content</div>

Inside of a directive the link function triggers after the view is compiled. The second parameter in the link function is the element which the directive is placed on, this gives performance benefits since there is no need to traverse the dom. It is a JQlite element which you can directly call methods on.

Directive

app.directive('click-me', function(){
  return{
    link(scope, el, attr){
       $(el).trigger('click');
     }
  }
});

Upvotes: 1

Related Questions