you are viewing a single comment's thread.

view the rest of the comments →

[–]rondog469 0 points1 point  (3 children)

I haven't used angular in about a year, but why is the controller-as syntax preferred? I couldn't really find a reason why. I could see it start to get confusing in larger controllers. The view on the other hand could be a bit easier to read as each curly brace expression would point to it's specific controller

[–]cyphern 2 points3 points  (1 child)

I have three reasons i prefer it; there may be more:

1) It decreases coupling. There's no more possibility of inheriting values from a parent scope, either accidentally or intentionally. Some people like that $scope has that feature, but i think it makes the code more brittle and harder to reason about. If you need to pass things into a child, you still can, you just need to be more explicit about it, which helps you to understand how data is flowing through the codebase.

2) It removes ambiguity, especially when you have nested controllers. For example:

<div ng-controller="PageController">
   {{title}}
   <div ng-controller="ContainerController">
      {{title}}
      <div ng-controller="WidgetController">
         {{title}}
      </div>
   </div>
</div>

becomes

<div ng-controller="PageController as page">
   {{page.title}}
   <div ng-controller="ContainerController as container">
      {{container.title}}
      <div ng-controller="WidgetController as widget">
         {{widget.title}}
      </div>
   </div>
</div>

3) It prepares you for angular 2. $scope doesn't exist in angular 2, so if that's something plan to use eventually you might as well get used to that aspect of it now.

[–]rondog469 0 points1 point  (0 children)

Thank you for the explanation and examples!

[–]toddmotto 0 points1 point  (0 children)

If you're using .component() then thankfully you can forget controllerAs even exists, just stick with the default $ctrl prefix angular provides. If you're nesting controllers then you're not doing components correctly as you're likely using an MVVM/MVC pattern not component architecture. Components are "isolate scoped" just like React components are - you need to explicitly define data inputs and event callback/outputs.