Cotten
Cotten

Reputation: 9077

Use a controller in another controller in Angular

The modal in angular-ui example is implemented with a ModalInstanceCtrl inside a ModalDemoCtrl controller like so:

var ModalDemoCtrl = function ($scope, $modal, $log) {
  $scope.open = function () {

    var modalInstance = $modal.open({
      ...
      controller: ModalInstanceCtrl,
     ...
    });
    ...
  };
};

var ModalInstanceCtrl = function ($scope, $modalInstance, items) {
  ...

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

When trying this approach by registering the Controllers with angular like so:

app.controller('ModalInstanceCtrl', ['$scope', '$modal', '$log',
 function ($scope, $modalInstance, items) {
  ...

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

app.controller('ModalDemoCtrl', ['$scope', '$modal', '$log', 'ModalInstanceCtrl',
 function ($scope, $modal, $log, ModalInstanceCtrl) {
  $scope.open = function () {

    var modalInstance = $modal.open({
      ...
      controller: ModalInstanceCtrl,
     ...
    });
    ...
  };
 }]);

I get the following error:

Error: Unknown provider: ModalInstanceCtrlProvider <- ModalInstanceCtrl

Should it be possible to nest controllers like this in angular?

Upvotes: 1

Views: 1796

Answers (1)

Chandermani
Chandermani

Reputation: 42669

You don't need to inject ModelInstanceCtrl into your ModalDemoCtrl. The controller definition should be

app.controller('ModalDemoCtrl', ['$scope', '$modal', '$log',
 function ($scope, $modal, $log) {

It should work without this too. If it does not try

 var modalInstance = $modal.open({
      ...
      controller: 'ModalInstanceCtrl',
     ...
    });

Upvotes: 4

Related Questions