Search code examples
javascriptangularjsangularjs-directiveangularjs-controller

set focus to textbox from angularJS controller


I am creating a web app in which I am using angularJS, I have a jqueryui datepicker , which looks like this

<input type="text" ng-model="rc.reg.mddoj" ng-blur="rc.dojChange()" title="Date Of Joining" placeholder="Date Of Joining" class="form-control" datepicker />

and in my controller

r.dojChange = function () {
    var currentTarget = event.target;
    setTimeout(function () { r.reg.mddoj = currentTarget.value; }, 500);
}

and after executing this I want to set focus to my next control

<input type="text" ng-model="rc.reg.mdemail" title="EmailID" placeholder="EmailID" class="form-control validatingData" />

how can I set control to elements from angularJS controller.

I just want to set focus to my element from a directive and want to call the directive in my r.dojChange function()


Solution

  • To focus an element from your AngularJS code you have to execute the following:

    $timeout(function() {
       const elementToFocus = $element[0].querySelector(<SELECTOR TO YOUR ELEMENT>);
       if (elementToFocus) {
          elementToFocus.focus();
       }
    }, 0);