Home > Web Front-end > JS Tutorial > body text

Why Use \'controller as\' Syntax in AngularJS?

DDD
Release: 2024-10-26 19:21:30
Original
267 people have browsed it

Why Use

Understanding AngularJS's "controller as" Syntax

Introduction

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.

Controller as Syntax

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>
Copy after login

This code tells Angular to create an instance of the InvoiceController and store it in the invoice variable within the current scope.

Removing $scope from Controller

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>
Copy after login

Assigning Aliases in the View

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>
Copy after login

Purposes of controller as Syntax

The "controller as" syntax was introduced primarily for these reasons:

  • Removal of $scope: Some developers prefer to avoid the $scope syntax, believing that it obfuscates the source of properties.
  • Clarity of Property Origin: By using aliases in the view, it becomes clear which properties belong to which controller. This is especially useful when nesting controllers.
  • Avoidance of Dot Rule Issues: The "controller as" syntax helps avoid problems with AngularJS's "dot rule," which can make it difficult to access properties from parent controllers. It allows for a clear and hierarchical access to controller properties.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!