"controller as" vs $scope

94 views
Skip to first unread message

migajek

unread,
Jun 3, 2014, 10:11:53 AM6/3/14
to ang...@googlegroups.com
Hi, Ive just learned about controller as syntax. Is it recommended instead of using $scope for passing data to templates? What are its adventages over $scope (except that one doesnt need to declare dependency on scope anymore)?

Sander Elias

unread,
Jun 3, 2014, 10:22:37 AM6/3/14
to ang...@googlegroups.com
Hi Migajek,

The advantage is that it is easier to comprehend. Also, in the view/html its more clear where your data is coming from.
There is also a difference in life-time between a controller and a scope. 
Also a scope comes with build-in goodies like $scope.$watch/$emit/$on/... Those are not directly available to a controller.

Is that enough to answer your question?

Regards
Sander

Matthieu Larcher

unread,
Jun 4, 2014, 2:21:26 AM6/4/14
to ang...@googlegroups.com
Check this link, it explains it quite nicely : http://toddmotto.com/digging-into-angulars-controller-as-syntax/

migajek

unread,
Jun 4, 2014, 3:48:37 AM6/4/14
to ang...@googlegroups.com
Hi Sander, thank you for the reply.
I'm aware of the functionalities available in $scope which are tricky when using Controller/as.
I'm also aware that using Controller/as is problematic when it comes to callbacks - I'm talking about context changing /this not pointing controller anymore/. 
I know there are workarounds for those (angular.bind, assing var t = this; etc) but still, they're workarounds. 

I'm wondering if there is anything that justifies usage of Controller/as and overcoming mentioned problems.
The only thing that crossed my mind is inheritance, it'd be obvious to inherit the controller itself, not the scope.

From my understanding the Controller/as makes Angular MVC-like (View has direct access to Controller), while the $scope is kind of ViewModel. 
This makes me wonder again, which one is the recommended way as of Angular 1.3?

Could you please elaborate more on the lifetime of $scope vs Controller? Is that about instatiating $scope when injecting dependency?

Sander Elias

unread,
Jun 4, 2014, 5:14:06 AM6/4/14
to ang...@googlegroups.com
Hi Migajek,

Well, if you use ng-controller, a scope will get created before your controller gets instantiated, and if will be destroyed after the controller is gone.
there is a small difference there, and for 99% of the practical uses, it makes no difference there.  
However, ng-controller is not the only way to create a new scope, there are much more directives that create a new scope. And those scopes
might have a very different life-time as the containing/child/sibling controller.

Regards
Sander
Reply all
Reply to author
Forward
0 new messages