After implementing the angular modal service discussed in this article:
app.service('modalService', ['$modal',
function ($modal) {
var modalDefaults = {
backdrop: true,
keyboard: true,
modalFade: true,
templateUrl: '/templates/modal.html'
};
var modalOptions = {
closeButtonText: 'Close',
actionButtonText: 'OK',
headerText: 'Proceed?',
bodyText: 'Perform this action?'
};
this.showModal = function (customModalDefaults, customModalOptions) {
if (!customModalDefaults) customModalDefaults = {};
customModalDefaults.backdrop = 'static';
return this.show(customModalDefaults, customModalOptions);
};
this.show = function (customModalDefaults, customModalOptions) {
//Create temp objects to work with since we're in a singleton service
var tempModalDefaults = {};
var tempModalOptions = {};
//Map angular-ui modal custom defaults to modal defaults defined in service
angular.extend(tempModalDefaults, modalDefaults, customModalDefaults);
//Map modal.html $scope custom properties to defaults defined in service
angular.extend(tempModalOptions, modalOptions, customModalOptions);
if (!tempModalDefaults.controller) {
tempModalDefaults.controller = function ($scope, $modalInstance) {
$scope.modalOptions = tempModalOptions;
$scope.modalOptions.ok = function (result) {
$modalInstance.close(result);
};
$scope.modalOptions.close = function () {
$modalInstance.dismiss('cancel');
};
}
}
return $modal.open(tempModalDefaults).result;
};
}]);
I'm struggling to figure out how to transfer data from the modal (which contains an input
) to the controller.
This is my current modal setup:
<input type="text" class="form-control" id="{{modalOptions.inputName}}" name="{{modalOptions.inputName}}" data-ng-model="modalOptions.inputVal" data-ng-if="modalOptions.inputName" />
<button type="button" class="btn"
data-ng-click="modalOptions.close()">{{modalOptions.closeButtonText}}</button>
<button class="btn btn-primary"
data-ng-click="modalOptions.ok();">{{modalOptions.actionButtonText}}</button>
Controller snippet:
$scope.addTopic = function () {
var modalOptions = {
closeButtonText: 'Cancel',
actionButtonText: 'Create Topic',
inputName: 'topicName'
};
modalService.showModal({}, modalOptions).then(function (result) {
// I have attempted...
var input = $scope.inputName; // and...
input = result;
$log.log("Adding topic '" + input + "' to publication no " + $scope.publication.id);
});
}
Despite setting inputName
in modalOptions
, when the user inputs a value and clicks ok, nothing gets sent to the controller. Both $scope.inputName
and result
end up as undefined
.
The desired outcome is to receive an object structured like
{ inputs : {name: 'inputName' , value: 'abcde'} }
.