Angularjs – The correct way to inject an angular controller dependency inside an angular.ui modal

angularjsangularjs-scope

following angular.ui Modal example shows the modalInstance calling a ModalIntanceCtrl which is later created as a function:

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

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

I have a 2 questions/problems:

  1. the docs recommend creating a controller in another way (due to minification issues) for example:

    myApp.controller('GreetingCtrl', ['$scope', function($scope) {
    $scope.greeting = 'Hola!';
    }]);

But if I create the controller like this, how could I Inject it into the modalInstance?

  1. The controller I call here isn't a Modal Instance controller but my global loginCtrl, is this a problem? should I subclass somehow the loginCtrl or call it from the ModalInstanceCtrl? and if so – how exactly?

I'll be glad for guidance and clarfication about this.
Thanks!

Best Answer

You question is not very clear, but if you declare controller using the module API, then you can provide the controller to the modal service as a string

myApp.controller('ModalInstanceCtrl', ['$scope', function($scope) { $scope.greeting = 'Hola!'; }]);

controller: 'ModalInstanceCtrl',

The same can be done for loginCtrl if you want to use that in the modal service.

Related Topic