3

I'm trying to create a Modal where the controller is in an external file. This aids in code organization, and I certainly don't want the controller on the window object like the example shows at the Angular Bootstrap site. I just took their example and moved the controller to another module, but I'm getting an error that the controller doesn't exist. I get the feeling I may need to use the $controller service to retrieve it, but I can't get it to work.

angular.module('plunker', ['ui.bootstrap', 'otherModule'])

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

  $scope.items = ['item1', 'item2', 'item3'];

  $scope.open = function () {

    var modalInstance = $modal.open({
      templateUrl: 'myModalContent.html',
      controller: ModalInstanceCtrl,
      resolve: {
        items: function () {
          return $scope.items;
        }
      }
    });

    modalInstance.result.then(function (selectedItem) {
      $scope.selected = selectedItem;
    }, function () {
      $log.info('Modal dismissed at: ' + new Date());
    });
  };
});

angular.module('otherModule', [])
.controller('ModalInstanceCtrl', function($scope, $modalInstance, items) {

  $scope.items = items;
  $scope.selected = {
    item: $scope.items[0]
  };

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

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

Plunkr here

1 Answer 1

2

You have to put ModalInstanceCtrl as a string. You are trying to make a reference to an object that is not defined. If controller parameter is a string, angular will look it up in the registered controllers:

var modalInstance = $modal.open({
      templateUrl: 'myModalContent.html',
      //Needs to be a string
      controller: 'ModalInstanceCtrl',
      resolve: {
        items: function () {
          return $scope.items;
        }
      }
    });
Sign up to request clarification or add additional context in comments.

1 Comment

I swear I had tried that before with no success, but updating the Plunkr with the suggestion fixes it. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.