angular-ui bootstrap $modal service using directive instead
angular-ui, angular-ui-bootstrap, angularjs, javascript
Solution
The issue you have is that you are trying to inject values which are not available for injection. Only values registered with the injector can be injected.
The logic of you code is also flawed, you are creating the modal in your main controller but trying to close it in the directive. Ideally, the modal should be triggered by the directive (via it's link function), and then you can ok/cancel it from there.
See my http://plnkr.co/edit/3p1rXAymd7BilyklgxKy?p=preview for one possible approach, I have kept the code that closes and cancels the modal in the main controller.
angular.module('ui.bootstrap.demo', ['ui.bootstrap']);
angular.module('ui.bootstrap.demo').directive('myModal', function() {
return {
restrict: 'E',
templateUrl: 'myModalContent.html',
controller: function ($scope) {
$scope.selected = {
item: $scope.items[0]
};
}
};
});
angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl', function ($scope, $modal, $log) {
$scope.items = ['item1', 'item2', 'item3'];
$scope.open = function (size) {
var modalInstance;
var modalScope = $scope.$new();
modalScope.ok = function () {
modalInstance.close(modalScope.selected);
};
modalScope.cancel = function () {
modalInstance.dismiss('cancel');
};
modalInstance = $modal.open({
template: '<my-modal></my-modal>',
size: size,
scope: modalScope
}
);
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
});
Problem
The examples I see of using angular-ui/bootstrap's `$modal` always look something like this: ``` $modal.open({ templateUrl: 'modaltemplate.html', controller: function($scope) { ... } }); ``` What if I want to use a directive, instead? Like this: ``` $modal.open({ template: '<my-modal-directive></my-modal-directive>' // no "controller" property; use directive's controller }); ``` The markup for `my-modal-directive` renders fine, and I've moved the `controller` property into the `my-modal-directive` definition object, but now getting this error from the `my-modal-directive`: ``` Error: [$injector:unpr] Unknown provider: $modalInstanceProvider <- $modalInstance ``` Can anyone point me to an example where `$modal` uses a directive where that directive defines the `controller`? For example, this works, where I've replaced the `templateUrl` with a directive: ``` http://plnkr.co/edit/YrGaF83GH6bzZPRR55GK?p=preview ``` But when I move the controller from `$modal.open()` into the directive, that's when the error happens: ``` http://plnkr.co/edit/aLBT239EpL004DRh4jll?p=preview ```