如何在 Angular 中创建一个始终将其自身放置在主体上的指令?
How do I create a directive in Angular that always places itself on the body?
我的模式对话框组件(在 Angular 1.5 中)遇到问题。它被放置在一个滚动区域内,这意味着在 iOS 上它会在溢出容器的任何地方被切断(旁注,这似乎是一个没有人谈论的主要错误!参见此处:)
在任何情况下,我都想修改我的 modal-dialog 指令以自动在 DOM 中移动自己,将自己(一旦编译)放在 body 标签上,这样它就不会受溢出规则影响。
这是我现有的对话框。让它自动将自己定位为 body 的子项的最佳方式是什么?
angular.module('app').directive('modalDialog', function()
{
return {
restrict: "E",
replace: true,
transclude: true,
template: "<div class='modal'><div class='modal-window'><div class='modal-inner' ng-transclude></div></div></div>",
link: function (scope, element, attrs)
{
var zIndexDivInner = element.find("[ng-transclude='']").first().zIndex()
//This handler exists solely for the purpose of keeping focus within the dialog.
function onFocus(event)
{
if ($(event.target).zIndex() < zIndexDivInner) // If focus is going to an element
{ // beneath the dialog,
var $elmInputs = element.find(":input") // set it back to the first input-type
$elmInputs[0].focus() // element within the dialog.
}
}
//On scope destruction, remove the onFocus event listener.
scope.$on('$destroy',
function ()
{
$("body")[0].removeEventListener("focus", onFocus, true)
})
$("body")[0].addEventListener("focus", onFocus, true)
}
}
});
angular.module('app').directive('rootIf', function()
{
return {
restrict: 'A',
link: function (scope, $elm, attrs)
{
scope.$watch(attrs.rootIf, onChangeRootIf);
function onChangeRootIf()
{
if (scope.$eval(attrs.rootIf))
$("body").children().first().before($elm);
else
$elm.detach();
}
}
}
});
我的模式对话框组件(在 Angular 1.5 中)遇到问题。它被放置在一个滚动区域内,这意味着在 iOS 上它会在溢出容器的任何地方被切断(旁注,这似乎是一个没有人谈论的主要错误!参见此处:
在任何情况下,我都想修改我的 modal-dialog 指令以自动在 DOM 中移动自己,将自己(一旦编译)放在 body 标签上,这样它就不会受溢出规则影响。
这是我现有的对话框。让它自动将自己定位为 body 的子项的最佳方式是什么?
angular.module('app').directive('modalDialog', function()
{
return {
restrict: "E",
replace: true,
transclude: true,
template: "<div class='modal'><div class='modal-window'><div class='modal-inner' ng-transclude></div></div></div>",
link: function (scope, element, attrs)
{
var zIndexDivInner = element.find("[ng-transclude='']").first().zIndex()
//This handler exists solely for the purpose of keeping focus within the dialog.
function onFocus(event)
{
if ($(event.target).zIndex() < zIndexDivInner) // If focus is going to an element
{ // beneath the dialog,
var $elmInputs = element.find(":input") // set it back to the first input-type
$elmInputs[0].focus() // element within the dialog.
}
}
//On scope destruction, remove the onFocus event listener.
scope.$on('$destroy',
function ()
{
$("body")[0].removeEventListener("focus", onFocus, true)
})
$("body")[0].addEventListener("focus", onFocus, true)
}
}
});
angular.module('app').directive('rootIf', function()
{
return {
restrict: 'A',
link: function (scope, $elm, attrs)
{
scope.$watch(attrs.rootIf, onChangeRootIf);
function onChangeRootIf()
{
if (scope.$eval(attrs.rootIf))
$("body").children().first().before($elm);
else
$elm.detach();
}
}
}
});