Stephen Patten
Stephen Patten

Reputation: 6363

How to get an instance of an AngularJS Controller after it has been constructed?

I've started to break my application down into separate files due to the size and complexity of said file, based entirely on the way that the angular-seed project has done it.

During this re-factoring I have run into a problem with the way the original controllers were constructed. Some of them, ones that will be injected into a modal dialog are created as instances.

var firstInstanceCtrl = ['$scope', function($scope) { code... } ];

var secondInstanceCtrl = ['$scope', function($scope) { code... } ]; 

and used in my 'main' controller this way

$scope.buttonClick = function (row) {

    var viewModel = {};

    var modalInstance = $modal.open({
        backdrop: 'static',
        windowClass: 'modal-wide',
        templateUrl: 'modalFirst.html',
        controller: firstInstanceCtrl,
        resolve: {
            viewModel: function () {
                return viewModel;
            }
        }
    });

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

but, the way the controllers are registered now, I don't see a way how to get an instances e.g.

angular.module('myApp.controllers', []).
controller('firstInstanceCtrl', [function() {

}])
.controller('secondInstanceCtrl', [function() {

}]); 

So my question is this, "How do I get an instance of a child controller inside of my main controller?"

Upvotes: 5

Views: 5405

Answers (1)

a better oliver
a better oliver

Reputation: 26838

You can use the name that was used for the registration of the controller:

controller: 'firstInstanceCtrl',

$modal.open uses $controller internally.

Upvotes: 6

Related Questions