Reputation: 13918
From the AngularJS documentation Understanding controllers:
Associating Controllers with Angular Scope Objects
You can associate Controllers with scope objects implicitly via the ngController directive or $route service.
Those two approaches are well known and mainly used across AngurlaJS applications.
What draw my attention is this part found in Developer Guide / Understanding the Controller Component:
Associating Controllers with Angular Scope Objects
You can associate controllers with scope objects explicitly via the scope.$new api or implicitly via the ngController directive or $route service.
So in addition to implicit association of Controller with scope there is mentioned also explicit way by using scope.$new api.
I am aware that scope.$new is used to create new [isolated] scope but I somehow don't understand how exactly is it related to explicit association of controller with scope.
It would be great to see some practical use case and/or more detailed explanation.
Upvotes: 1
Views: 271
Reputation: 44916
It's primarily used during testing when you want to construct a controller directly and do something with it.
You can use the $controller service to do this:
var scope = $rootScope.$new();
var ctrl = $controller(MyAwesomeController, { $scope: scope });
Now I can manipulate the scope
variable directly and check for side effects:
scope.foo = 'bar'
scope.$digest();
expect(scope.bar).toBe('YEAH BABY!!!');
The $controller service will instantiate a controller with all of the dependencies injected like you would expect. It also allows you to pass in a hash of locals that will override any of the dependencies with something you provide explicitly.
Again, this is very useful for testing because you can swap out a service with a mock if needed.
Upvotes: 2