angularjsangular-uiangular-strap

Return data from angular strap modal


I am sorry if this has been already asked, but is it possible to return data from angular strap modal, and if so, could anyone provide short code snippet how to do so?

There is very nice option to return data from angular-ui modal, but I was not able to find the strap-way. Thank you very much for answers.


Solution

  • I've come up with a simple way to achieve this and the API is just like angular-ui modal.

    You decorate the $modal service:

    .config(['$provide', function($provide) {
    
        $provide.decorator('$modal', ['$q', '$rootScope', '$delegate', function ($q, $rootScope, $delegate)
        {
            return function returnAResultWhenClosingTheModal(options)
            {
                var deferred = $q.defer();
    
                if (!options.scope) {
                    options.scope = $rootScope.$new();
                }
    
                options.scope.$close = function(result)
                {
                    deferred.resolve(result);
                    this.$hide();
                };
    
                // Call the real $modal service to create the modal
                var modal = $delegate(options);
    
                modal.result = deferred.promise;
    
                return modal;
            }
        }
        ]);
    }])
    

    To create a modal is the same as always except now each modal has a result property which is a promise that gets resolved when the modal is closed:

    var myModal = $modal(modalOptions);
    
    myModal.result.then(function(result)
    {
        // I now have access to the result the modal closed with.
    });
    

    In the modal controller you simply call the new $close method on the $scope with the result you want to return:

    // In the controller
    $scope.$close(resultToReturn);