Associating Controllers with Angular Scope Objects explicitly

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.

Answers


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.


Need Your Help

J2ME read file byte by byte

file java-me jsr75

I have encountered many site examples and almost all are like this: http://www.java2s.com/Code/Java/J2ME/ReadDisplayFile.htmhttp://www.roseindia.net/j2me/read-file.shtml

cant see the aws-s3 url saved in rails database

ruby-on-rails amazon-web-services amazon-s3 carrierwave fog

I have successfully implemented image uploading using carrierwave, fog and Amazon S3. In my imageuploader am using only fog as storage. But when i check my database i can see that just the file nam...