javascriptangularjsangular-controllerangularjs-module

Angular JS - module.controller parameters


I'm new to Angular JS and in a tutorial they place that the way to create a controller is:

angular.module('app', [])
  .controller('TodoController', ['$scope', function ($scope) {
    $scope.todos = [
      { title: 'Learn Javascript', completed: true },
      { title: 'Learn Angular.js', completed: false },
      { title: 'Love this tutorial', completed: true },
      { title: 'Learn Javascript design patterns', completed: false },
      { title: 'Build Node.js backend', completed: false },
    ];
  }]);

I want to UNDERSTAND what does each of the parameters is:

I guess the first one is the name of the controller, and the last one is the TodoController constructor.

But what is '$scope' ? A variable name to use on the HTML, a method name?

Can I send more parameters in the array?

I searched on Angular docs but it is pretty lame with no doc about methods. Searching class code neither gave much more info.


Solution

  • The second argument (Array of strings + function) is used for dependency injection.

    angular.controller('TodoController', ['$scope', function ($scope) { ... }])
    

    In case your code gets minified angular will know which dependencies to inject, as strings are not affected by minification.

    So, the above code after minification will become something like this:

    angular.controller("TodoController",["$scope",function(o){...}]);
    

    And it will still be readable by angular's dependency injection algorithm.

    PS. Array is optional, you can pass there just plain function.