0
votes

I have an application that uses angular-ui bootstrap modal (http://angular-ui.github.io/bootstrap/#/modal) for search from a list and select one of row.

In common using of angular-ui bootstrap modal, we must create two controller (for example ModalDemoCtrl for main modal and ModalInstanceCtrl for modal window).

In second controller, we have two method:

$scope.ok = function () {
    $modalInstance.close($scope.selected.item); 
};

$scope.cancel = function () {
    $modalInstance.dismiss('cancel');
};

that repeat in several place (when I create several search modal).

How to I create a directive (or service), that contains these two controller and create these two methods inside it.

2
Instead of creating a directive or a service, you can have two common controller for main and modal screen. It makes more sense. You can config your main and modal screen as per your requirement before initializing. So your both controller code will work on your configuration. It will solve your problem, and no need to right code repeatedly.dhavalcengg

2 Answers

1
votes

You are wrong - there is one controller for modal window. Second one is for main page and is not related to modals at all. So if u want to have 10 buttons on page to open 10 different modals, then u will have 11 controllers.

For modals that just displays message or ask to confirm actions it is good to have service, so u can write Myservice.showModal('Are you sure?', function callbackafterok() {...}).

If u just dont like repeating $modalInstance.close - make simple directive for buttons with ng-click binding, to write:

<button closeModalWithData="" >Ok</cancel>

or just <modalOk/> with template <button ng-click="ok()">Ok</button>...

0
votes

Petr Averyanov's answer was right. I created a directive and towards the end of the documentation for Angular UI modal directive, When we create a modal window, some property adds to $scope. One of property is $close that we can use it to close modal. Like this:

    .directive('closeModal', function() {
        return {
            restrict: 'E',
            template: '<button ng-click="$close()">Cancel</button>'
        };
    })