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:
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.
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
}
While removing $scope from the controller simplifies code, it requires you to specify an alias in the view:
// With $scope
// With controller as
The "controller as" syntax was introduced primarily for these reasons:
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