0

I was developing a module where I need to create some text input manually (on enter or button clicking ) and auto focus on that input right after it's appended to the list. So far the function seems to work but when I open the console log, the $digest already in progress error appears. Kind of weird but if I remove some $eval or $apply the code won't work.

Here's my plnk demo for your reference: Demo

function keyEnter($document) {
  return {
    restrict: "A",
    scope: false,
    link: function(scope, ele, attrs) {
      ele.bind("keydown keypress", function(event) {
        if (event.which === 13) {
          scope.$apply(function() {
            scope.$eval(attrs.keyEnter);
          });
          event.preventDefault();
        }
      });
    }
  }
}

function customAutofocus() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {      
      scope.$watch(function() {
        return scope.$eval(attrs.customAutofocus);
      }, function(newValue) {
        if (newValue === true) {
          element[0].focus();
        }
      });
    }
  };
}

I followed the auto focus from this thread, it doesn't show any error even when I applied the same logic. The only difference is I'm using angular 1.3 while his is 1.2

What should I do to improve the code to avoid those $digest error ? Any help is really appreciate, thanks in advance

Community
  • 1
  • 1
Duc Hong
  • 1,149
  • 1
  • 14
  • 24

1 Answers1

2

I adapted your plunk, so it works.

have a look at the new directive:

  function customAutofocus($timeout) {
     return {
        restrict: 'A',
        link: function(scope, element, attrs) {
           //rember this gets run only only 
           //once just after creating the element, so I just neet to focus once, when
           // this digest cycle is done!
           $timeout(function() {
              // use a timout to foucus outside this digest cycle!
              element[0].focus(); //use focus function instead of autofocus attribute to avoid cross browser problem. And autofocus should only be used to mark an element to be focused when page loads.
           }, 0);
        }
     };
  }

This makes use of how angular works.

Sander Elias
  • 754
  • 6
  • 9