【发布时间】:2015-05-02 07:45:09
【问题描述】:
我目前正在玩 angular,尤其是 angular 和 bootstrap 模块(现在没有 bootstrap 谁能活下去?)。
在任何情况下,是否有人有一个干净的解决方案来将焦点设置在弹出打开的新模式对话框中的输入字段上? 开箱即用似乎不支持此基本功能。 我以为我可以在“开放”的未来上钩——但它似乎很早就被召唤了。
所以,当您打开一个模态实例时 - 例如
$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);
});
现在我要关注的输入元素将使用指令进行角度增强。
<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 未来似乎正在发布事件,说明模型在您实际看到浮动在屏幕上的模态对话框之前已打开。 输入元素被告知设置为焦点 - 但很快,如果我调试它在调用 focus() 时仍然在后台。 IT 是可见的,从某种意义上说,您可以在页面的 dom 中进行查找,并且从某种意义上说,如果您询问 JQuery(":visible") dom 元素,它确实是可见的。但它仍然是肉眼看不见的。
我在其他地方看到了一种与我完全不同的方法,它不依赖于事件并且依赖于从真到假的属性值。 我根本不喜欢这种方法,因为它与页面的业务逻辑过于耦合,我不喜欢并拒绝将其作为解决方案。
对此的解决方案应该完全依赖于这样一个事实,即模态对话框的主体中只有一个输入元素,该元素带有 set focus on me please 指令,并尽可能与页面逻辑分离。
理想情况下,这应该是 bootsrap angular 本身支持的功能,遗憾的是它似乎不是,但由于我们必须 - 在任何情况下 - 使用 API 来打开对话框并关闭它们,我们应该能够扩展这一步以横切干净的方式获得焦点功能。
对此有何建议?
【问题讨论】:
标签: javascript angularjs twitter-bootstrap focus