从控制器触发模态弹窗

4

我有一个使用Bootstrap的模态框,我从我的modalcontroller中获取数据填充到其中。当我填充完数据后,我想要显示它。为了能够在进入页面时立即显示模态框,我想直接触发它。现在我有一个按钮来触发它,但是如何以合适的方式自动触发它呢?

<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog" ng-init="getAllItems()">
    <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Modal Header</h4>
            </div>
            <div class="modal-body">
                <div class="">
                    <form class="form-horizontal" name="form" role="form">
                        <div ng-repeat="item in items">
                            <input type="radio" name="fundselector" ng-model="item" ng-value="item"/> {{item}} <br />
                        </div>
                    </form>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>

    </div>
</div>

我的控制器:

angular.module("Modal")
.controller("ModalController",
[
"$scope", "$rootScope", "$location", "ModalService", "AuthenticationService",
function ($scope, $rootScope, $location, ModalService, AuthenticationService) {

    AuthenticationService.GetCurrentWindowsUser(function(username) {
        $scope.username = username;
    });

    $scope.getAllItems = function () {
        AuthenticationService.GetCurrentWindowsUser(function (username) {
            if (username) {
                AuthenticationService.GetItems(username, function (items) {
                    $scope.items = items;
                    //Trigger modalpopup here
                });
            }
        });
    }
}
]);

1
你尝试过 $('#myModal').modal('show') 吗? - Vivek
2
希望使用Angular而不是jQuery。 - MrProgram
@Vivek,你的回答是最好的伙计!谢谢 :) - Fai Zal Dong
4个回答

5

不要使用jquery,使用angular-ui。

https://angular-ui.github.io/bootstrap/#/modal

您可以像下面这样以编程方式打开模态框,并在resolve中传递数据。这是从他们的示例中直接复制粘贴的。

var modalInstance = $uibModal.open({
      animation: $scope.animationsEnabled,
      templateUrl: 'myModalContent.html',
      controller: 'ModalInstanceCtrl',
      size: size,
      resolve: {
        items: function () {
          return $scope.items;
        }
      }
    });

2

通过angular.element查找元素并隐藏。

var popup = angular.element("#modal-default");
//for hide model
popup.modal('hide');
//for show model
popup.modal('show');

喜欢这个解决方案。干净易懂。 - LiefLayer

1
尝试像这样做 -

$('#yourModalId').modal('show');


0
为了修复你的示例,我创建了一个服务,它会打开模态框并将其附加到外部控制器和模态框控制器上。我不得不从模态框中删除“modal”类,因为它有一个display:none属性。这里是一个演示我所做的事情的fiddle。然而,@mgiesa的答案更好。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接