Home >Web Front-end >JS Tutorial >Why Use \'controller as\' Syntax in AngularJS?
AngularJS introduced a new syntax for defining controllers, "controller as", which has raised some questions about its purpose. This article aims to clarify the rationale behind this syntax and its benefits.
The "controller as" syntax allows you to instantiate a controller and assign it to a variable in the current scope. For example:
<code class="javascript">controller('InvoiceController as invoice')</code>
This code tells Angular to create an instance of the InvoiceController and store it in the invoice variable within the current scope.
One noticeable difference with the "controller as" syntax is that it eliminates the $scope parameter from the controller definition. This allows for cleaner and more concise controllers:
<code class="javascript">// With $scope function InvoiceController($scope) { // Do something with $scope.qty } // With controller as function InvoiceController() { // Do something with this.qty }</code>
While removing $scope from the controller simplifies code, it requires you to specify an alias in the view:
<code class="html">// With $scope <input type="number" ng-model="qty" /> // With controller as <input type="number" ng-model="invoice.qty" /></code>
The "controller as" syntax was introduced primarily for these reasons:
The above is the detailed content of Why Use \'controller as\' Syntax in AngularJS?. For more information, please follow other related articles on the PHP Chinese website!