gpt4 book ai didi

javascript - Angular ui-bootstrap-tpls-0.12.1 打开模态对话框设置焦点

转载 作者:行者123 更新时间:2023-11-28 19:15:12 24 4
gpt4 key购买 nike

我目前正在使用 Angular,特别是带有 Bootstrap 模块的 Angular(现在谁可以没有 Bootstrap 生活?)。

无论如何,是否有人有一个干净的解决方案来将焦点设置在弹出的新模式对话框中的输入字段上?这个基本功能似乎不支持开箱即用。我以为我可以在“开放”的 future 勾搭 - 但似乎被提前叫到了。

因此,当您打开模态实例时 - 例如

$modal.open({
"templateUrl": 'myModalContent.html',
"controller" : 'modalInstanceCtrl',
"size": size,
"resolve" : {
"items": function () {
return $scope.items;
}
}
});

然后,您可以将模态实例与广播偶数等一起使用:

 modalInstance.opened.then(function(){
$rootScope.$broadcast(myNewDirectiveBootstrapConfig.events.modalInstanceOpened
, modalInstance);
});

现在我想要关注的输入元素将通过指令进行 Angular 增强。

<label for="popupTitle">Title:</label>
<input type="text" class="form-control" id="popupTitle"
ng-required="true"
ng-model="popup.title"
ng-minlength="1"
newdirective-modal-focus
>

指令代码将是非侵入性的并且独立于页面逻辑。理想情况下,您将只使用事件 API,并且您的非侵入式指令将被调用并执行焦点魔法。

angular.module('newDirectivesModule', [])
.constant('myNewDirectiveBootstrapConfig', {
events: {
modalInstanceOpened : "modalInstanceOpened"
}
})
.directive('newdirectiveModalFocus', ['myNewDirectiveBootstrapConfig',
function (myNewDirectiveBootstrapConfig) {
return {
restrict:'A', // process compile directive only on element attributes


link: function(scope, elm, attr) {
scope.$watch(function(){return elm.is(":visible");}, function(value) {
if(elm.is(":visible")){
elm.focus();
}
});

scope.$on(myNewDirectiveBootstrapConfig.events.modalInstanceOpened, function(event, data) {
if(elm.is(":visible")){
elm.focus();
}
});
}
};
}]);

您可以在代码中看到我玩过不同的观看场景。实际情况是,指令代码正在被调用给儿子。opens.then future 似乎会发布事件,表明模型在您实际看到屏幕上 float 的模式对话框之前已打开。输入元素被告知要设置焦点 - 但显然很快,如果我调试,当调用 focus() 时它仍然在后台。它是可见的,因为您可以在页面的 dom 中进行查找,并且如果您询问 JQuery(":visible") dom 元素,它确实是可见的。但肉眼仍然看不见。

我在其他地方看到过一种与我的完全不同的方法,它不依赖于事件,而是依赖于属性值从 true 变为 false。我根本不喜欢这个方法,因为它与页面的业务逻辑耦合太多,我不喜欢并拒绝将其作为解决方案。

解决这个问题的方法应该完全依赖于这样一个事实:模式对话框的主体中只有一个输入元素,并且设置了“请关注我,请”指令,并尽可能与页面逻辑分离。

理想情况下,这应该是 Bootsrap Angular 本身支持的功能,遗憾的是似乎并非如此,但由于我们必须 - 在任何情况下 - 使用 API 来 OEPN 对话框并关闭它们,所以我们应该能够扩展此步骤以横切干净的方式获得焦点功能。

对此有什么建议吗?

最佳答案

我使用不同的指令方式来获取焦点发布链接以确保元素被渲染(无论是否为模态):

app.directive('focusMe',
['$timeout',
function ($timeout) {
return {
link: {
pre: function preLink(scope, element, attr) {
// ...
},
post: function postLink(scope, element, attr) {
$timeout(function () {
element[0].focus();
}, 0);


}
}
}
}]);

所以输入应该如下所示:

<input type="text" 
focus-me
class="form-control" id="popupTitle"
ng-required="true"
ng-model="popup.title"
ng-minlength="1">
<小时/>

中的演示 Plunker

关于javascript - Angular ui-bootstrap-tpls-0.12.1 打开模态对话框设置焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29999753/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com