Using Angular Bootstrap Modal with external controller

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

Answers


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;
        }
      }
    });

Need Your Help

Type Mismatch VBScript Error when getting RecordSet

forms vbscript recordset

I am working on some legacy code that is written in Classic ASP / VBSCript.

Batch Create folder by file names with the same name and extension

file batch-file command-line rename filenames

I have a lot of jpg files to be moved in a folder with the same name. here my example