I like to avoid DOM lookups, watches, and global emitters whenever possible, so I use a more direct approach. Use a directive to assign a simple function that focuses on the directive element. Then call that function wherever needed within the scope of the controller.
Here's a simplified approach for attaching it to scope. See the full snippet for handling controller-as syntax.
Directive:
app.directive('inputFocusFunction', function () {
'use strict';
return {
restrict: 'A',
link: function (scope, element, attr) {
scope[attr.inputFocusFunction] = function () {
element[0].focus();
};
}
};
});
and in html:
<input input-focus-function="focusOnSaveInput" ng-model="saveName">
<button ng-click="focusOnSaveInput()">Focus</button>
or in the controller:
$scope.focusOnSaveInput();
angular.module('app', [])_x000D_
.directive('inputFocusFunction', function() {_x000D_
'use strict';_x000D_
return {_x000D_
restrict: 'A',_x000D_
link: function(scope, element, attr) {_x000D_
// Parse the attribute to accomodate assignment to an object_x000D_
var parseObj = attr.inputFocusFunction.split('.');_x000D_
var attachTo = scope;_x000D_
for (var i = 0; i < parseObj.length - 1; i++) {_x000D_
attachTo = attachTo[parseObj[i]];_x000D_
}_x000D_
// assign it to a function that focuses on the decorated element_x000D_
attachTo[parseObj[parseObj.length - 1]] = function() {_x000D_
element[0].focus();_x000D_
};_x000D_
}_x000D_
};_x000D_
})_x000D_
.controller('main', function() {});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>_x000D_
_x000D_
<body ng-app="app" ng-controller="main as vm">_x000D_
<input input-focus-function="vm.focusOnSaveInput" ng-model="saveName">_x000D_
<button ng-click="vm.focusOnSaveInput()">Focus</button>_x000D_
</body>
_x000D_
Edited to provide more explanation about the reason for this approach and to extend the code snippet for controller-as use.