Reputation: 398
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.
Upvotes: 2
Views: 705
Reputation: 1500
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);
Upvotes: 0
Reputation: 391
You can return any data from your angular-strap
modal very easy.
Suppose you have some object, that should be updated after modal's submit. For example, you have a controller, that popups your modal. All you have to do is to define some handler, that should update your data, pass this handler to youp modal via resolve
option and call this handler in modal's controller.
Example:
This controller contains user details and shows modal for change this data.
app.controller('userDetailsCtrl', ['$scope', '$modal', function($scope, $modal) {
$scope.userDetails = {
firstName: 'John',
lastName: 'Smith'
};
$scope.showChangeUserDetailsModal = function() {
var options = {
userDetails: angular.copy($scope.userDetails),
submit: function(result) {
$scope.userDetails = angular.copy(result);
}
};
$modal({
controller: 'changeUserDetailsCtrl',
contentTemplate: '', //Here is your template with some input fields
show: true,
resolve: {
options: function() {
return options;
}
}
});
};
}]);
Modal's controller calls handler submit
, passing result of modal's work.
app.controller('changeUserDetailsCtrl', ['$scope', 'options', function($scope, options) {
$scope.userDetailsDraft = options.userDetails;
$scope.submitChanges = function() {
options.submit($scope.userDetailsDraft);
$scope.$hide(); //Close modal after submit
};
}]);
Upvotes: 3