1

I am pretty new to angular materials. I am trying to use the autocomplete feature.

I have some autocomplete sample code here; http://codepen.io/helpme/pen/KzxXPQ

The first thing that stumped me is this declaration of the controller;

<div ng-controller="DemoCtrl as ctrl" layout="column" ng-cloak="" ng-app="MyApp">

In my past angularjs code, the ng-controller is declared this way <div ng-controller="DemoCtrl" without the as ctrl.

What is the difference between having as ctrl and not having it? How should the code at http://codepen.io/helpme/pen/KzxXPQ be changed if the as ctrl is removed?

Krzysztof Safjanowski
  • 7,292
  • 3
  • 35
  • 47
  • 10
    this is clarified here: http://stackoverflow.com/questions/21287794/angularjs-controller-as-syntax-clarification – Allen Fernandes Apr 26 '16 at 07:26
  • 1
    You can read more about `as ctrl` [here](https://docs.angularjs.org/api/ng/directive/ngController). If you don't want use `as ctrl`, remove it in html and in controller remove `var self = this` and change `self` to `$scope` (Don't forget put $scope in controller). – DieuNQ Apr 26 '16 at 07:56

1 Answers1

2

John Papa's excellent Angular style guide (essential reading for all new Angular devs IMO) covers this rather well:

Why?: Controllers are constructed, "newed" up, and provide a single new instance, and the controllerAs syntax is closer to that of a JavaScript constructor than the classic $scope syntax.

Why?: It promotes the use of binding to a "dotted" object in the View (e.g. customer.name instead of name), which is more contextual, easier to read, and avoids any reference issues that may occur without "dotting".

Why?: Helps avoid using $parent calls in Views with nested controllers.

Points 2 and 3 are the key for me - it makes your code a lot easier to read and maintain.

Community
  • 1
  • 1
Mourndark
  • 2,526
  • 5
  • 28
  • 52