Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the "locals" argument to $controller do?

Tags:

angularjs

In Angular, $controller takes two arguments - constructor and locals.

Documentation

The documentation basically just says that:

  1. locals is an object.
  2. "Injection locals for Controller."

But I still don't understand what it does. Can anyone elaborate and explain?

like image 930
Adam Zerner Avatar asked Jul 06 '15 16:07

Adam Zerner


1 Answers

"Locals" allows you to define injectables into the controller - i.e. it defines the objects that $injector can locate just for that controller (as opposed to app-wide injectables that could be defined with .factory, for example).

The best illustration is with an example:

var controller = $controller("Controller1", {
   foo: {
     v: "I am foo"
   }
});

Then, your actual controller can inject foo:

.controller("Controller1", ["$scope", "foo", function($scope, foo){
   $scope.fooVal = foo.v;
}]);

It's a very rare case (except in unit testing) that you would need to use $controller directly in your code - here's one odd example where you can. This is used, however, by ui-router and ng-route to define controllers for a state/route with "resolved" values.

like image 91
New Dev Avatar answered Oct 10 '22 02:10

New Dev