I am new in angular. I need to set focus on textbox. I searched the web and found a sample from this link https://stackoverflow.com/a/18295416/6188148
The code I found is bit harder to understand and I copy those code in JS Fiddle but code is not running. JS Fiddle link is https://jsfiddle.net/tridip/099Lbgqn/1/
Full code
<div ng-app="myApp" ng-controller="MyCtrl">
<input type="text" focus-on="focusMe"/>
</div>
var app = angular.module("myApp", []);
app.controller('MyCtrl', function($scope, focus) {
focus('focusMe');
});
app.directive('focusOn', function() {
return function(scope, elem, attr) {
scope.$on('focusOn', function(e, name) {
//alert(name+' '+attr.focusOn);
//alert(elem);
if(name === attr.focusOn) {
elem[0].focus();
}
});
};
});
app.factory('focus', function ($rootScope, $timeout) {
return function(name) {
//alert(name);
$timeout(function (){
$rootScope.$broadcast('focusOn', name);
});
}
});
Few areas of the above code is not clear.
1) what is scope.$on and what it does ? scope.$on('focusOn', function(e, name) {}
2) if(name === attr.focusOn)
No variable is there called name, so how could we refer something called name in code ?
3) see these below line
return function(scope, elem, attr) {
scope.$on('focusOn', function(e, name) {
//alert(name+' '+attr.focusOn);
//alert(elem);
if(name === attr.focusOn) {
elem[0].focus();
}
});
};
Directive has return function
statement, what is it? Is it immediate function ?
Why scope.$on
has been declare with in return function ?
Would you tell me why my JS Fiddle link is not working?