Matt Bryson
Matt Bryson

Reputation: 2934

Best way to show / hide a common modal in Angular JS

I have an angular-ui-bootstrap modal template, controller and instance controller as per the angular demo (http://plnkr.co/edit/?p=preview)

I want any other controller in my application to be able to show / hide this common modal view.

At the moment, I have done this via the $rootScope.$emit and $on.

Is there a better pattern for this kind of shared component behaviour?

Below is my current implementation....

I have the template included in my main html file

<div ng-include src="'/views/partials/modal.html'" ng-controller="ModalController as vm"></div>

So the ModalController has ...

app.controller('ModalController', ['$rootScope', '$modal', function($rootScope, $modal) {

    $rootScope.$on("modal:open", function(event, params, okCallback, cancelCallback) {

        okCallback = okCallback || _.noop;
        cancelCallback = cancelCallback || _.noop;

        var modalInstance = $modal.open({
            animation: true,
            templateUrl: 'modal.html',
            controller: 'ModalInstanceController',
            controllerAs: "vm",
            //size: 'sm',
            resolve: {
                params: function() {
                  return params
                }
            }
        });

        modalInstance.result.then(function (result) {
              okCallback(result);
            }, function () {
              cancelCallback();
        });

    });

}]);

And I call it from any other controller like this....

$rootScope.$emit("modal:open", {
        title:"Are you sure?",
        body:"Are you sure you want to do this?",
        confirm:true,
        okClass:"btn-warning"
    }, success function() {
    }, error function() {
});

Upvotes: 2

Views: 1159

Answers (1)

Lucian
Lucian

Reputation: 644

Is there a better pattern for this kind of shared component behaviour?

Yes. Use a service. You can then inject that service into each controller you want to use it and call a method to open it; something like:

modalService.openModal({
    title:"Are you sure?",
    body:"Are you sure you want to do this?",
    confirm:true,
    okClass:"btn-warning"
}, function success(){}, function error(){});

The openModal method has the same code as the $rootScope.$on('modal:open') function.

(https://docs.angularjs.org/guide/services)

Upvotes: 2

Related Questions