2014-10-18 73 views
0

我正在开发一个模块,我需要手动创建一些文本输入(在输入或按钮单击时),并在该输入附加到列表后自动对焦该输入。到目前为止,该功能似乎可行,但是当我打开控制台日志时,出现$digest already in progress错误。有点奇怪,但如果我删除一些$ eval或$应用代码将无法正常工作。自动专注于最新的输入元素

这里是我的,供大家参考plnk演示: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(); 
     } 
     }); 
    } 
    }; 
} 

我跟着自动对焦从这个thread,它不显示任何错误,甚至当我应用了相同的逻辑。唯一的区别是我使用角1.3而他的是1.2

我该怎么做才能改善代码以避免这些$摘要错误?任何帮助是非常感谢,提前致谢

回答

2

我a dapted your plunk,所以它的工作原理。

看看新指令:

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); 
     } 
    }; 
    } 

这使得使用如何角的作品。

+0

哇,不知道这是这么简单...非常感谢你 – 2014-10-18 15:44:59