3 dicembre 2014

angular js: set input focus

var app = angular

.module("app")

.factory("mySetFocus", ["$timeout", function($timeout){
return {
focus : {},
set : function(name){
this.focus[name] = !!!this.focus[name];
}
};
}])

.directive('myFocus', ["$timeout", "mySetFocus", function($timeout, mySetFocus) {
return {
restrict: 'A',
link : function(scope, element, attrs) {
scope.setter = mySetFocus;
scope.$watch("setter.focus."+attrs.name, function(v){
if(v==undefined) return;
$timeout(function() {
element[0].focus();
});
});
}
};
}])

.controller("myCtrl", ["$scope", "mySetFocus", function($scope, mySetFocus){
mySetFocus.set("myfield");
}]);



<form>
<input name="myfield" my-focus />
</form>

Nessun commento:

Posta un commento