简体   繁体   中英

Angular Modal - closing/dismissing modal

I am new to Angular and trying to implement a modal. Having problem closing/dismissing the modal - when I click the cancel button, nothing happens. Here is the controller code:

angular.module('navApp')
    // Passing the $modal to controller as dependency
    .controller('HomeCtrl', ['$scope', '$uibModal', function ($scope, $uibModal) {
        $scope.title = "Hello, Angm-Generator!";
        $scope.open = function () {
            var modalInstance = $uibModal.open({
                templateUrl: 'myModalContent.html',
                controller: 'ModalCtrl'
            });
        };
    }])

    .controller('ModalCtrl', function ($scope, $uibModalInstance) {
        // Added some content to Modal using $scope
        $scope.content = "ModalCtrl, Yeah!"
        // Add cancel button
        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };
    })

and here is the template view of the actual modal

<!-- Modal Script -->
<script type="text/ng-template" id="myModalContent.html">
    <div class="modal-header">
        <button type="button" class="close" datadismiss="modal" aria-hidden="true">&times;</button>
        <h3 class="modal-title">Hello from Modal!</h3>
    </div>
    <div class="modal-body">
        Modal Content from: <b>{{ content }}</b>
    </div>
    <div class="modal-footer">
        <button class="btn btn-danger" ngclick="cancel()">Cancel</button>
    </div>
</script>

Even clicking the cross on the top right of modal doesn't close the modal. Any ideas? Thanks:)

Should it not be ng-click="cancel()" instead of ngclick ?

Also I don't think the scope is bound to the controller, I haven't tested this but I believe you need some more options:

var modalInstance = $uibModal.open({
   templateUrl: 'myModalContent.html',
   controller: 'ModalCtrl',
   controllerAs: '$mCtrl',
   bindToController: true
});

And then just update your template:

ng-click="$mCtrl.cancel()"

Have you tried $uibModalInstance.close()?

Another thing you can do is

 $scope.open = function () {
        var modalInstance = $uibModal.open({
            templateUrl: 'myModalContent.html',
            controller: 'ModalCtrl'
        });
        modalInstance.result.then(function successCallBack() {
            modalInstance.close()
         }, function errorCallBack() {
            modalInstance.close()
        })
    };`

If you want to close the model , on click of the cross bar then , you can use

<button type="button" class="close" data-dismiss="modal">&times;</button>

This will be button , and data-dismiss="modal" will close your modal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM