首頁  >  文章  >  web前端  >  為什麼在 AngularJS 中使用“controller as”語法?

為什麼在 AngularJS 中使用“controller as”語法?

DDD
DDD原創
2024-10-26 19:21:30268瀏覽

Why Use

理解AngularJS 的“controller as”語法

簡介

AngularJS 引入了一種定義控制器的新語法“controller as”,這引起了一些關注關於其目的的問題。本文旨在闡明此語法背後的基本原則及其優點。

Controller as 語法

「controller as」語法可讓您實例化控制器並將其指派給目前的變數範圍。例如:

<code class="javascript">controller('InvoiceController as invoice')</code>

此程式碼告訴 Angular 建立 InvoiceController 的實例並將其儲存在目前範圍內的發票變數中。

從 Controller 中刪除 $scope

與「controller as」語法的一個顯著區別是它從控制器定義中消除了 $scope 參數。這允許更乾淨、更簡潔的控制器:

<code class="javascript">// With $scope
function InvoiceController($scope) {
  // Do something with $scope.qty
}

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

在視圖中分配別名

雖然從控制器中刪除$scope 簡化了程式碼,但它要求您在視圖中指定別名:

<code class="html">// With $scope
<input type="number" ng-model="qty" />

// With controller as
<input type="number" ng-model="invoice.qty" /></code>

控制器作為語法的用途

引入「controller as」語法主要是出於以下原因:

  • 刪除$scope: 有些開發人員寧願避免使用$scope 語法,認為它會混淆屬性的來源。
  • 屬性來源的清晰性: 透過在視圖中使用別名,可以清楚地了解哪些屬性屬性屬於哪個控制器。這在嵌套控制器時特別有用。
  • 避免點規則問題:「controller as」語法有助於避免 AngularJS 的「點規則」問題,該問題可能導致存取屬性變得困難來自父控制器。它允許對控制器​​屬性進行清晰且分層的存取。

以上是為什麼在 AngularJS 中使用“controller as”語法?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn