2014-10-18 75 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