Angular 在模态中将焦点和输入置于另一个模态之上
Angular focus and input in modal on top of another modal
您好,我有一个集中输入模态的指令。当它是单一模式时,焦点效果很好。在一个实例中,虽然我有一个模态,然后单击此模态上的按钮会触发顶部的另一个模态。然后焦点不起作用。
有什么想法吗?
这是我的代码:
.directive('auto-focus', function ($timeout) {
return {
restrict: 'A',
link: function(scope, el) {
var whiteList = ['input', 'a', 'textarea', 'div']
, tagToFocus = el[0].tagName.toLowerCase()
, allow = whiteList.indexOf(tagToFocus) > -1;
if (!allow) {
throw new Error(`Autofocus is not allowed on ` + tagToFocus);
}
$timeout(() => el[0].focus(), 50);
}
}
我假设指令 auto-focus
发生在两个弹出窗口中。这意味着两个指令都在争夺焦点,最后执行的指令获胜。这是我的猜测。
所以我会尽量延迟focus()
后面的弹窗
您可以添加带有可选 timeout
参数的 auto-focus
指令参数化。如果未提供,它将默认为 50 毫秒。如果提供,将使用自定义值。
然后 html 在您的第二个弹出窗口中将如下所示:
<div> ....
<input auto-focus timeout="250"/>
</div>
像这样更新你的指令
//just a draft :)
....
restrict: 'A',
scope: {
timeout: '=' //This will create new isolate scope
}
link: function(scope, el) {
if (scope.timeout == undefined) {
//set default value
scope.timeout = 50;
}
else {
scope.timeout = parseInt(scope.timeout, 10);
....
}
我认为你的指令没问题,问题可能是你打开模式的方式。
我想第二个模式已经使用 rendered html
。假设您在页面的某处隐藏了 html 模板。如果您的第二个模态使用隐藏的 html 模板,那么 focus
将不起作用!您可以通过 console.log
您的元素进行检查。
如果你的第二个模态使用你的第一个模态的任何部分html它也不会工作!
因此这仅适用于新注入的 html 或者您必须在模式打开后重新运行 您的指令。
检查此 Demo 以获得进一步的说明。
您好,我有一个集中输入模态的指令。当它是单一模式时,焦点效果很好。在一个实例中,虽然我有一个模态,然后单击此模态上的按钮会触发顶部的另一个模态。然后焦点不起作用。
有什么想法吗?
这是我的代码:
.directive('auto-focus', function ($timeout) {
return {
restrict: 'A',
link: function(scope, el) {
var whiteList = ['input', 'a', 'textarea', 'div']
, tagToFocus = el[0].tagName.toLowerCase()
, allow = whiteList.indexOf(tagToFocus) > -1;
if (!allow) {
throw new Error(`Autofocus is not allowed on ` + tagToFocus);
}
$timeout(() => el[0].focus(), 50);
}
}
我假设指令 auto-focus
发生在两个弹出窗口中。这意味着两个指令都在争夺焦点,最后执行的指令获胜。这是我的猜测。
所以我会尽量延迟focus()
后面的弹窗
您可以添加带有可选 timeout
参数的 auto-focus
指令参数化。如果未提供,它将默认为 50 毫秒。如果提供,将使用自定义值。
然后 html 在您的第二个弹出窗口中将如下所示:
<div> ....
<input auto-focus timeout="250"/>
</div>
像这样更新你的指令
//just a draft :)
....
restrict: 'A',
scope: {
timeout: '=' //This will create new isolate scope
}
link: function(scope, el) {
if (scope.timeout == undefined) {
//set default value
scope.timeout = 50;
}
else {
scope.timeout = parseInt(scope.timeout, 10);
....
}
我认为你的指令没问题,问题可能是你打开模式的方式。
我想第二个模式已经使用 rendered html
。假设您在页面的某处隐藏了 html 模板。如果您的第二个模态使用隐藏的 html 模板,那么 focus
将不起作用!您可以通过 console.log
您的元素进行检查。
如果你的第二个模态使用你的第一个模态的任何部分html它也不会工作!
因此这仅适用于新注入的 html 或者您必须在模式打开后重新运行 您的指令。
检查此 Demo 以获得进一步的说明。