Search code examples
javascriptangularjsjavascript-frameworkangularjs-controller

How exactly is an AngularJS controller defined?


I have a question related to the syntax of controllers and the way they are declared in AngularJS. I'm fairly certain I know how they work, but my question is related to the syntax.

So I might have something like this:

// MODULE:
var weatherApp = angular.module("weatherApp", ['ngRoute', 'ngResource']);

// Home Page Controller:
weatherApp.controller('homeController', ['$scope', function($scope) {
    // Controller business operation   
}]);

The first line declares the weatherApp variable which is my module and that's associated to my page. And module() is a method that take as parameter the module name and the list of dependencies used by this module. Is that right?

The main question is related to the controller definition.

weatherApp.controller('homeController', ['$scope', function($scope) {
    // Controller business operation   
}]);

On the previous weatherApp variable (my module) I call the controller() method to set the controller settings. So the first parameter is the controller name (homeController in this case), followed by an array that first has to contain the list of dependencies (in this case only the $scope service provided by AngularJS) and its last element is a function that takes these dependencies as input parameters which implement the controller behavior.

Why does Angular do it this way? Why are the dependencies and the function that implements the controller passed all together in a single array?

Maybe I have some difficulties in understanding this behavior because I came from a Java background where an array can't contain different kinds of objects and where a function is not an object.


Solution

  • Bad:

    weatherApp.controller('homeController', function($scope){
        // Controller business operation   
    });
    

    When this is minified, parameters are minified and angular will no longer be able to know which dependencies to inject.

    Good:

    weatherApp.controller('homeController', ['$scope', function($scope) {
        // Controller business operation   
    }]);
    

    The array syntax: the dependencies in a string make minification safe.

    Other correct way:

    You can as well inject separatly the dependencies:

    function WeatherCtrl($scope, $http) {
        // Controller business operation   
    }
    WeatherCtrl.$inject = ['$scope'];
    weatherApp.controller('WeatherCtrl', WeatherCtrl);