Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am still very new to Angular.js and am working through setting up my first application. I would like to be able to do the following:

angular.module('App.controllers', [])
  .controller('home', function () {
    $scope.property = true;
  }]);

angular.module('App', ['App.controllers'])
  .config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/', {templateUrl: 'partials/home.html', controller: home});
  }]);

Using this setup the following error is generated:

Uncaught ReferenceError: home is not defined from App

My question is: How can I register controllers using angular.module.controller() (or $controllerProvider.register() directly) and use the registered controller elsewhere in my app.

My motivation: I would like to avoid using either global constructor functions as my controllers (as most of the examples on angularjs.org use) or complex namespacing. If I can register and use controllers as single variable names (that are not then put in the global scope) that would be ideal.

share|improve this question

2 Answers 2

up vote 73 down vote accepted

Try using a string identifier.

routeProvider.when('/', {templateUrl: 'partials/home.html', controller: 'home'});

When you use a literal, it is looking for a variable called home, but that doesn't exist in this case.

share|improve this answer
1  
Thanks, that did the trick. So simple. –  Noah Freitas Jun 26 '12 at 19:17
1  
The above solution doesn't appear to work... I'm getting "Error: Argument 'PhoneListCtrl' is not a function, got string". Help! –  mpowered Oct 3 '12 at 20:51
24  
If you define the controller as a function (function PhoneListCtrl(){}), you have to reference it as a function. If you define it with .controller (app.controller('PhoneListCtrl', function(){}), you should reference it as a string. –  Andrew Joslin Oct 4 '12 at 14:41
    
I used string identifier to assign a controller from another module, and it works. very nice! –  Aladdin Homs Nov 13 '12 at 5:32
3  
Using a string worked for me on the routeProvider, but now this is not working: <div ng-controller="MyCtrl"></div>. The other form works - <div class="ng-controller='MyCtrl'"></div>, but I'd prefer using the attribute form because it's simpler. Is there a way? –  Joe Hanink Apr 18 '13 at 7:20

If you are getting controller is not defined error you have to write your controller name within the quotes.

or define your controller like this

function controllerName()
{
   //your code here
}

refer this: Uncaught ReferenceError:Controller is not defined in AngularJS

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.