AngularJS 1.4 – Declaring a Controller

I’ve been following a few tutorials that describe declaring a MainController. However the tutorials a pre AngularJS 1.3x and are no longer valid. Previous AngularJS allowed you to define a controller globally . As of 1.3x this is no longer the case and you must declare your Controllers inside angular modules. Here’s an example:


var githubViewerApp = angular.module('githubViewer', []);

Declare a new module and give it a unique name. Then assign module to a variable.


var MainController = function MainController($scope, $http) { }

Create your MainController. This is where all your functions and service calls will sit.


githubViewerApp.controller("MainController", ['$scope', '$http', MainController]);

Now bind the MainController variable to the module variable. The variables with $ signs are included in the function parameters to help support minification. Without this minifiers would rename the variable and angular would be unable to bind the parameters to the view.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s