4

I'm writing my code according to Google standards...not even sure what this syntax is called, but it's different from the Angular-UI example code for controllers and I'm getting an injector error for $modalInstance :(

var myControllers = angular.module('myControllers', ['ngCookies','ui.bootstrap']);

myApp.controller('LoginDialogCtrl', ['$scope', '$modalInstance', 'Auth', function($scope, $modalInstance, Auth) {
  $scope.login = function() {
    // Close dialog
    $modalInstance.dismiss('Logged in');
  };
}]);

myApp.controller('AuthCtrl', ['$scope', '$modal', 'Auth', function($scope, $modal, Auth) {
  $scope.openLoginDialog = function () {
    var modalInstance = $modal.open({
      templateUrl: 'partials/auth/login.html',
      controller: myApp.LoginDialogCtrl,
      }
    });
  };
  ...
}]);

The dialog opens fine, but after the user logs in but I get an injector error for this line:

myApp.controller('LoginDialogCtrl', ['$scope', '$modalInstance', 'Auth', function($scope, $modalInstance, Auth) {

I have tested it like this and it seems to work which is really annoying:

var ModalInstanceCtrl = function ($scope, $modalInstance) {
  $scope.ok = function () {
    $modalInstance.close();
  };

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

Does it have something to do with the way my controller is being initialized and at the time of it's initialization it doesn't know about $modalInstance? How do I make this work?

SomethingOn
  • 9,813
  • 17
  • 68
  • 107

2 Answers2

2

See this answer: AngularJS inject issue with Angular Bootstrap modal

I ran into the same issue as you. I had a ng-controller directive inside the partial. After removing it, the problems went away.

Community
  • 1
  • 1
tchen
  • 2,212
  • 1
  • 16
  • 18
  • To elaborate a touch, the modal is already injecting the controller on open, and no other injector will have the modalInstance available. Having the controller declared again in your modal markup will cause the error you are seeing. So remove ng-controller from your template. – virtualadrian Mar 30 '15 at 02:52
1

Two things attract my attention.

  1. You can use ModalInstanceCtrl variable in controller property because it is a function. But if you register controller then you cannot use myApp.LoginDialogCtrl. Instead use its name 'LoginDialogCtrl'. Like this:

    controller: 'LoginDialogCtrl'  
    
  2. I am a bit confused that you declare module myControllers but then define controllers on some other module myApp. It seems logical to have myControllers everywhere instead of myApp.
Sergey_M
  • 511
  • 4
  • 8