我正在开发一个模块,我需要手动创建一些文本输入(在输入或按钮点击时),并在将其附加到列表后立即自动关注该输入。到目前为止,该功能似乎有效,但是当我打开控制台日志时,会出现$digest already in progress
错误。有点奇怪,但如果我删除一些$ eval或$ apply代码将无效。
以下是我的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
如何改进代码以避免这些$ digest错误?任何帮助都非常感谢,提前感谢
答案 0 :(得分:2)
我是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);
}
};
}
这可以利用角度的工作方式。