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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With