tylerwal
tylerwal

Reputation: 1870

Reuse Angular Controller for Modal and Non-Modal

How would I go about reusing an angular controller for the purposes of a modal as well as a non-modal? I have a new business requirement to have the same form that exists already in a modal (just the modal body) placed in a tab within a new page.

Currently I'm using resolve within my modal initialization to pass a variable to the modal's controller.

Modal Initialization

var modalInstance = $uibModal.open({
    templateUrl: 'myModal.html',
    controller: 'myCtrl',
    resolve: {
        foo: function() { return scope.fooFromScope; },
    }
});

Existing Controller

myApp.controller('hrpoConductReviewModalCtrl', ['$scope', 'foo', function($scope, foo) {
    ...
}]);

Currently not using $uibModalInstance within my modal.

Is there a way to initialize a controller from within another controller and pass the foo variable? There is an existing question that asks the same thing but the main answer focuses on using scope within the modal initialization rather than resolve.


Existing Question: How to use the same controller for modal and non-modal form in Angular UI Bootstrap?

Upvotes: 4

Views: 807

Answers (1)

Thomas
Thomas

Reputation: 2137

In case you are using ui-router you can just use the resolve from ui-router:

$stateProvider
    .state('conductReview', {
        url: '/review',
        templateUrl: '/js/templates/review.html',
        controller: 'hrpoConductReviewModalCtrl',
        resolve: {
            foo: function() { return scope.fooFromScope; },
            $uibModalInstance: function () { return null; } // <- workaround if you want to use $uibModalInstance in your controller.
        }
    })

In case you are not using ui-router you should definitely check it out ;-)

Upvotes: 2

Related Questions