Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using AngularJS Controllers created with angular.module().controller()

Tags:

angularjs

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.

like image 682
Noah Freitas Avatar asked Jun 26 '12 16:06

Noah Freitas


People also ask

What is module and controller in AngularJS?

An AngularJS module defines an application. The module is a container for the different parts of an application. The module is a container for the application controllers. Controllers always belong to a module.

What is use of controller in AngularJS?

AngularJS ControllersAngularJS applications are controlled by controllers. The ng-controller directive defines the application controller. A controller is a JavaScript Object, created by a standard JavaScript object constructor.

What is Ng-controller in AngularJS?

AngularJS ng-controller Directive The ng-controller directive adds a controller to your application. In the controller you can write code, and make functions and variables, which will be parts of an object, available inside the current HTML element. In AngularJS this object is called a scope.

What is the use of Angular controllers in the application *?

All the AngularJS application mainly relies on the controllers to control the flow of data in that application. Basically, it controls the data of AngularJS applications and the controller is a Javascript object, created by a standard JavaScript object constructor.


1 Answers

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.

like image 131
Andrew Joslin Avatar answered Sep 26 '22 02:09

Andrew Joslin