
AngularJS
使用AngularJS和Bootstrap Modal时,有时我们希望在单击模态框外部或按下转义键时防止模态框消失。这可以通过添加一些自定义代码来实现。在本文中,我们将介绍如何使用AngularJS和Bootstrap Modal来实现这一功能,并提供一个简单的案例代码。
首先,让我们看一下如何使用AngularJS和Bootstrap来创建一个基本的模态框。我们将使用ng-click指令来触发模态框的显示和隐藏。html<!DOCTYPE html><html lang="en" ng-app="myApp"><head> <Meta charset="UTF-8"> <title>AngularJS Bootstrap Modal Example</title> <link rel="stylesheet" class="url" target="_blank" rel="nofollow noreferrer" href="/to/?target=https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/CSS/bootstrap.min.CSS"></head><body ng-controller="myController"> <button class="btn btn-primary" ng-click="showModal()">Open Modal</button> <div class="modal" ng-show="modalVisible"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Modal Title</h4> </div> <div class="modal-body">在上面的代码中,我们创建了一个ng-click指令,其值为showModal()函数。当按钮被点击时,该函数将被调用,将modalVisible变量设置为true,从而显示模态框。接下来,让我们看一下如何防止模态框在单击外部或按下转义键时消失。为此,我们需要添加一些自定义代码。在AngularJS中,可以使用ng-click指令来捕获模态框外部的单击事件,并在该事件中阻止模态框的隐藏。This is the modal content.
</div> <div class="modal-footer"> <button class="btn btn-default" ng-click="hideModal()">Close</button> </div> </div> </div> </div> <script src="https://Ajax.Googleapis.com/Ajax/libs/AngularJS/1.6.9/angular.min.JS"></script> <script> var app = angular.module('myApp', []); app.controller('myController', function($scope) { $scope.modalVisible = false; $scope.showModal = function() { $scope.modalVisible = true; }; $scope.hideModal = function() { $scope.modalVisible = false; }; }); </script></body></html>
html<div class="modal" ng-show="modalVisible" ng-click="preventHideModal($event)">在上面的代码中,我们添加了一个ng-click指令,其值为preventHideModal($event)函数。该函数将被调用,并传递一个事件对象作为参数。在该函数中,我们可以使用事件对象的stopPropagation()方法来阻止事件的进一步传播,从而阻止模态框的隐藏。接下来,让我们在控制器中实现preventHideModal()函数。
Javascript$scope.preventHideModal = function(event) { event.stopPropagation();};在上面的代码中,我们使用event.stopPropagation()方法来阻止事件的进一步传播。现在,当我们单击模态框外部时,模态框不会消失了。而当我们单击模态框内部时,模态框仍然会消失,因为事件会继续传播到模态框内部。在阻止模态框隐藏时添加标题现在我们已经完成了阻止模态框隐藏的功能,让我们在模态框的标题中添加一个标签来提高可读性。html<div class="modal-header"> <h4 class="modal-title"><strong>Modal Title</strong></h4></div>在上面的代码中,我们在
Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号