Closing Twitter Bootstrap Modal From Angular Controller

后端 未结 8 814
时光说笑
时光说笑 2020-12-12 21:26

I have a modal window that I use to present a form to users. They enter the information and then press a button the has an ng-click. The server processes the request and s

8条回答
  •  [愿得一人]
    2020-12-12 21:39

    Here's a reusable Angular directive that will hide and show a Bootstrap modal.

    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();
                    });
    
                }
    
            }
        };
    
    });
    

    Usage Example #1 - this assumes you want to show the modal - you could add ng-if as a condition

    
    

    Usage Example #2 - this uses an Angular expression in the modal-visible attribute

    
    

    Another Example - to demo the controller interaction, you could add something like this to your controller and it will show the modal after 2 seconds and then hide it after 5 seconds.

    $scope.showDialog = false;
    $timeout(function () { $scope.showDialog = true; }, 2000)
    $timeout(function () { $scope.showDialog = false; }, 5000)
    

    I'm late to contribute to this question - created this directive for another question here. Simple Angular Directive for Bootstrap Modal

    Hope this helps.

提交回复
热议问题