Focus field
HTML
<div ng-app="app">
<div ng-controller="ctrl" ng-init="inp_focus = true" >
<input type="text" value="first field should be focused" />
<input type="text" focus="inp_focus" value="Second field" />
<button type="button" ng-click="inp_focus = false">unfocus</button>
<button type="button" ng-click="inp_focus = true">focus</button>
</div>
</div>
JavaScript
angular
.module('app', [])
.controller('ctrl', function($scope,$rootScope){
$scope.button = 'Toggle focus';
console.log($rootScope.focueEx)
})
.directive('focus', function($timeout, $parse,$rootScope) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
scope.$watch(attrs.focus, function(newValue, oldValue) {
if(newValue) {
element[0].focus();
}
});
element.bind("blur", function(e) {
$timeout(function() {
scope.$apply(attrs.focus + "=false");
}, 0);
});
element.bind("focus", function(e) {
$timeout(function() {
scope.$apply(attrs.focus + "=true");
$rootScope.focueEx = attrs.focus;
// console.log(attrs.focus)
}, 0);
})
}
}
});