"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Use \"controller as\" Syntax in AngularJS?

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

Published on 2024-11-19
Browse:745

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:

controller('InvoiceController as invoice')

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:

// With $scope
function InvoiceController($scope) {
  // Do something with $scope.qty
}

// With controller as
function InvoiceController() {
  // Do something with this.qty
}

Assigning Aliases in the View

While removing $scope from the controller simplifies code, it requires you to specify an alias in the view:

// With $scope


// With controller as

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.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3