wtadahiro wtadahiro - 7 months ago 1869
Javascript Question

How to use angular component with ui.bootstrap.modal in angular 1.5?

I'd like to use angular component with ui.bootstrap.modal. angular version is 1.5.

I tried to use like below.

component

function MyComponentController($uibModalInstance){
var ctrl = this;

ctrl.doSomething = function() {
//doSomething
}
}

app.component('myComponent', {
contoller: MyComponentController,
templateUrl: '/path/to/myComponent.html'
}


parent controller

function parentController($uibModal){
var ctrl = this;

ctrl.openModal = function(){
var modalInstance = $uibModal.open({
template: '<my-component></my-component>'

}
}


And when I execute
parentController.openModal()
, I got the error of $injector:unpr Unknown Provider although modal window is open.

Is there a way to use angular component with ui.bootstrap.modal?
If you need more information, please let me know that.

Thank you.

EDIT

I've got a way to use component with ui.bootstrap.modal from Renato Machado, Thanks Renato.

But I feel It's a little bit complicated and not convenient. So finally I think that it's better to use component inside the modal.

Modal is opened with regular way(just set controller and template in
$uibModal.open({})
) and the modal contains the component which has logics you want to use commonly.

Modal should have only simple logics that are related with modal like close modal window.

Another logics mainly related with business/Application should be in component.

It makes easy to commonalize.

Answer

You need to pass the parent controller to the modal component with the modal instance on it. To do that you need to append the generate HTML of the modal in the parent component

parent component

$ctrl.openModal = function(){
    $ctrl.modalInstance = $uibModal.open({
        template: '<your-modal></your-modal>',
        appendTo : $document.find('parentComponent')
    });
}

modal component

.component('yourModal', {
        templateUrl: 'path/to/modal.html',
        replace: true,
        require: {
            parent : '^parentComponent'
        },
        controller: ModalCtrl
    });

function ModalCtrl() {
    var $ctrl = this;

    $ctrl.$onInit = function(){

        var instance = $ctrl.parent.modalInstance;

        $ctrl.items = ['item1', 'item2', 'item3'];

        $ctrl.selected = {
            item: $ctrl.items[0]
        };

        $ctrl.ok = function () {
            instance.close($ctrl.selected);
        };

        $ctrl.cancel = function () {
            instance.dismiss('cancel');
        };

        instance.result.then(function (selectedItem) {
            $ctrl.selected = selectedItem;
        }, function () {
            console.log('Modal dismissed at: ' + new Date());
        });
    };


}

Be carefull because the required controller will only be available after the $onInit.

Comments