2

I want to copy the value from vm.foo to vm.bar (that works) and then set focus to vm.bar (that does not work).

<input type="text" ng-model="vm.foo" id="foo" >
<button ng-click="vm.baa=vm.foo; angular.element('#bar').focus();"></button>

<input type="text" ng-model="vm.bar" id="bar" >

How come angular.element('#bar').focus() is not working in this situation?

torbenrudgaard
  • 2,375
  • 7
  • 32
  • 53

2 Answers2

3

Use a custom directive to emit an event.

app.directive('focusOn', () => {
   return (scope, elem, attr) => {
      scope.$on(attr.focusOn, (e) => {
          elem[0].focus();
      });
   };
});

Usage:

<input type="text" ng-model="vm.foo">

<button ng-click="vm.baa=vm.foo; vm.changeFocus();"></button>

<input type="text" ng-model="vm.bar" focus-on="myFocusEvent">

and then in your controller

vm.changeFocus = () => {
    $scope.$broadcast('myFocusEvent');
};

Notice that I'm using arrow functions instead of named functions

pridegsu
  • 1,108
  • 1
  • 12
  • 27
0

I found this Accessing Dom elements in Angular

so in our case that would be

<button ng-click="vm.baa=vm.foo; angular.element(document.querySelector('#bar')).focus();"></button>

I wonder if that fixes your problem. Actually I would change it to

ng-click="vm.baa=vm.foo; setFocus();"

and in the controller

vm.setFocus = function() {
    angular.element(document.querySelector('#bar'));
}
Jarek Kulikowski
  • 1,399
  • 8
  • 9