1
votes

ng-controller="invoiceController as invoice" create new invoiceController constructor and assigned the same to scope behind the scene, which the similar thing $scope injection does in controller function parameter

am i right for the above point.

if yes then how scope is related to this. Please help.

-- AngularJS Developer Guide - Conceptual Overview

2

2 Answers

0
votes

"as" tells what "this" is supposed to point to. This way, you can create more than one instance of the controller in different scopes, without getting them confused thanks to their different names.

0
votes

It allows you to use your controller as a class or prototype, where you expose class/prototype methods and properties to your templates rather than your controller adding methods and properties to the scope object.

So with ES2015 or ES5 you could do either:

export class SomeController {

 someProperty = true;

 someMethod() {
   return 'foo';    
 }
}

Or

function SomeController() {}
SomeController.prototype.someProperty = true;
SomeController.prototype.someMethod = function() { return 'foo'; }

Now if you provide one of these to your template as SomeController as ctrl you will then be able to access these as ctrl.someProperty and ctrl.someMethod(). The ctrl instance of your controller is added to the $scope for you.

Another benefit is memory footprint. Monkey patching functions onto $scope is wasteful. Class and prototypes allow the same method implementation to be shared, while keeping each instance separate. This adds up for components with many instances such as a list-item, for example.