任何人都有一个简单的指令来自动显示 Bootstrap 模式?在 Bootstrap 3 中,他们取消了自动显示模态的能力,所以我不能使用有角度的 ng-if 显示块。任何帮助都会很棒。
问问题
35201 次
2 回答
18
更新了 Angular 1.2 和 Bootstrap 3.1.1:http ://embed.plnkr.co/WJBp7A6M3RB1MLERDXSS/
我扩展了 Ender2050 的答案,因此该指令没有孤立的范围。这意味着模态内容可以包含对范围对象的引用。还重用指令属性,因此只需要一个属性。
app.directive("modalShow", function ($parse) {
return {
restrict: "A",
link: function (scope, element, attrs) {
//Hide or show the modal
scope.showModal = function (visible, elem) {
if (!elem)
elem = element;
if (visible)
$(elem).modal("show");
else
$(elem).modal("hide");
}
//Watch for changes to the modal-visible attribute
scope.$watch(attrs.modalShow, function (newValue, oldValue) {
scope.showModal(newValue, attrs.$$element);
});
//Update the visible value when the dialog is closed through UI actions (Ok, cancel, etc.)
$(element).bind("hide.bs.modal", function () {
$parse(attrs.modalShow).assign(scope, false);
if (!scope.$$phase && !scope.$root.$$phase)
scope.$apply();
});
}
};
});
用法:
<div modal-show="showDialog" class="modal fade"> ...bootstrap modal... </div>
于 2013-11-25T06:03:42.417 回答
13
这是一个 Angular 指令,它将隐藏和显示 Bootstrap 模式。
app.directive("modalShow", function () {
return {
restrict: "A",
scope: {
modalVisible: "="
},
link: function (scope, element, attrs) {
//Hide or show the modal
scope.showModal = function (visible) {
if (visible)
{
element.modal("show");
}
else
{
element.modal("hide");
}
}
//Check to see if the modal-visible attribute exists
if (!attrs.modalVisible)
{
//The attribute isn't defined, show the modal by default
scope.showModal(true);
}
else
{
//Watch for changes to the modal-visible attribute
scope.$watch("modalVisible", function (newValue, oldValue) {
scope.showModal(newValue);
});
//Update the visible value when the dialog is closed through UI actions (Ok, cancel, etc.)
element.bind("hide.bs.modal", function () {
scope.modalVisible = false;
if (!scope.$$phase && !scope.$root.$$phase)
scope.$apply();
});
}
}
};
});
使用示例 #1 - 假设您要显示模式 - 您可以添加 ng-if 作为条件
<div modal-show class="modal fade"> ...bootstrap modal... </div>
使用示例 #2 - 在 modal-visible 属性中使用 Angular 表达式
<div modal-show modal-visible="showDialog" class="modal fade"> ...bootstrap modal... </div>
另一个示例 - 为了演示控制器交互,您可以在控制器中添加类似这样的内容,它会在 2 秒后显示模式,然后在 5 秒后将其隐藏。
$scope.showDialog = false;
$timeout(function () { $scope.showDialog = true; }, 2000)
$timeout(function () { $scope.showDialog = false; }, 5000)
我很想看看人们提出的其他解决方案。干杯!
于 2013-10-28T20:36:56.283 回答