AngularStrap - calling modal from within a service?
I have a web application that uses AngularJS, Bootstrap 3 and AngularStrap. In this application, I have previously used the Bootstrap UI for Bootstrap directives, but I needed to switch to AngularStrap to have some additional functionality (like being able to provide a custom template for popovers). This migration changed the way the modal directive is applied, which is the subject of my question.
With Bootstrap UI, I had a security service that could implement a login modem when a user tried to access restricted content in an application using a controller defined in another module. Here's a rough paraphrase of my code to do this (most of it comes from the very useful seed project, angular-app ):
// Login form controller:
angular.module('LoginForm', []).controller('LoginFormController', ['$scope', 'security', function($scope, security) {
/* $scope controller logic goes here. Things like login, cancel, clear, etc. */
}]);
// Security service:
angular.module('Security', ['ui.bootstrap','LoginForm']).factory('security', ['$modal', function($modal) {
var loginDialog = null;
function openLoginDialog() {
loginDialog = $modal.open({
templateUrl : 'security/login/form.tpl.html',
controller : 'LoginFormController'
});
loginDialog.result.then(onLoginDialogClose);
}
return {
showLogin : function() {
openLoginDialog();
}
};
}]);
Now using AngularStrap I cannot figure out how to use the controller logic defined in the LoginForm LoginFormController module, because with AngularStrap there is no option controller
when initializing the modal. There is a parameter scope
, but I'm not sure how best to use this parameter in this situation. I think the modal initialization would be like this:
// AngularStrap version of $modal:
loginDialog = $modal({
template : 'security/login/form.tpl.html',
scope : /* LoginFormController scope somehow injected here */
});
For reference, here are the docs for Bootstrap UI: http://angular-ui.github.io/bootstrap/#/modal
and for AngularStrap: http://mgcrea.github.io/angular-strap/##modals
Is it possible to do this, or is it possible to call $ modal as a directive in a template using AngularStrap?
source to share
I found that using the standard ng-controller syntax works like a charm here.
Instead of setting the controller inside the code, use the attribute in the root code of the template:
<div class="modal" tabindex="-1" role="dialog" ng-controller="MyCustomModalController as ctrl">
...
<button class="btn btn-primary" ng-click="ctrl.ok()" >OK</button>
The only trick is communicating with the original controller. Bootstrap UI used a really nice callback that doesn't work with angular -strap. The solution uses a shared service, which is detailed here: Can one controller call another?
source to share