AngularJS引入了一种定义控制器的新语法“controller as”,这引起了一些关注关于其目的的问题。本文旨在阐明此语法背后的基本原理及其优点。
“controller as”语法允许您实例化控制器并将其分配给当前的变量范围。例如:
controller('InvoiceController as invoice')
此代码告诉 Angular 创建 InvoiceController 的实例并将其存储在当前范围内的 Invoice 变量中。
与“controller as”语法的一个显着区别是它从控制器定义中删除了 $scope 参数。这允许更干净、更简洁的控制器:
// With $scope
function InvoiceController($scope) {
// Do something with $scope.qty
}
// With controller as
function InvoiceController() {
// Do something with this.qty
}
虽然从控制器中删除$scope可以简化代码,但它要求您在视图中指定别名:
// With $scope
// With controller as
引入“controller as”语法主要是出于以下原因:
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3