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?
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.