44

I am still very new to AngularJS 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.

0

2 Answers 2

75

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.

Sign up to request clarification or add additional context in comments.

7 Comments

The above solution doesn't appear to work... I'm getting "Error: Argument 'PhoneListCtrl' is not a function, got string". Help!
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.
I used string identifier to assign a controller from another module, and it works. very nice!
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?
That should work, Joe. Could you create a plunker? plnkr.co/edit -> New -> AngularJS
|
-1

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

Comments

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.