Sunday, 14 September 2014

Create a focused and focusonload directive in Angular js HTML5

In this article we are going to see how to create a directive which will focus the element on page load and focus the element when change the property value. The  directive is a attribute, so we are going to create a two directive elements now.

var dirApp = angular.module('dirApp',[]);

dirApp.controller('dirController', function ($scope) {

    $scope.status = false;
    $scope.status1 = false;

    $scope.infocus=function()
    {
        $scope.status1 = true;
    };

    $scope.outfocus = function(){
      $scope.status1 = false;
    };

});



Create the directive :

dirApp.directive('focusOnLoad', function () {
   return{
     restrict:'A',
     link: function (scope, element, attrs, cntrl) {
         element[0] .focus();
     }
   };
});

dirApp.directive('focused', function ($timeout) {
   return{
       restrict:'A',
       scope:{
           focused:'=focused'
       },
       link: function (scope,element,attrs) {

           scope.$watch('focused', function () {
               console.log(scope.focused);
               if(scope.focused){
                   element[0].focus();
               }
               else{
                   element[0].blur();
               }
           });

           element.on('blur', function () {
               $timeout(function () {
                   scope.focused = false;
               });


           });

           function Apply(scope, fn) {
               (scope.$$phase || scope.$root.$$phase) ? fn() : scope.$apply(fn);
           }

           element.on('focus', function () {
              Apply(scope,function(){
                  if(!scope.focused)
                  scope.focused = true;
              });
           })

       }
   };
});


How to use the directive ?

Now use the directive as attribute in needed element , if we want a element which should be focused on load , so place the focus-on-load directive element.

Next we need an attribute which will be focused on property valued changed as True or False.
focused="status1"

Code:







output:






No comments:

Post a Comment