0

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?

Community
  • 1
  • 1
Monojit Sarkar
  • 2,353
  • 8
  • 43
  • 94

1 Answers1

0

Since your question is somehow broad, I'll answer you point by point.

first of all, the jsfiddle works fine and after running you will see the textbox been focued.

then, for your question:

1) what is scope.$on and what it does ? scope.$on('focusOn', function(e, name) {}

In angular, we use $scope.on to trigger events. Here it's triggering event named focusOn.

2) if(name === attr.focusOn) no variable is there called name...so how could we refere something called name in code ?

name is the parameter of event focusOn which is broadcasted by factory focus

3) directive has return function statement...what it is ? is it immediate function ?

see angular's documentation of directive and factory.


  • the controller called factory(service) focus, and event focusOn will be broadcasted by factory focus.
  • the directive focusOn is triggering event focusOn, once the event is broadcasted, the textbox will be focused by this line: elem[0].focus();.
Pengyy
  • 37,383
  • 15
  • 83
  • 73