簡體   English   中英

角度控制器-為什么將其命名為控制器?

[英]Angular controller - why do they name it controller?

這里

通常,控制器不應嘗試做太多事情。 它應僅包含單個視圖所需的業務邏輯。

我不明白為什么是控制器。 它必須是模型。 請解釋。

編輯:
這是官方開發人員指南中的示例:

angular.module('invoice1', [])
.controller('InvoiceController', function() {
  this.qty = 1;
  this.cost = 2;
  this.inCurr = 'EUR';
  this.currencies = ['USD', 'EUR', 'CNY'];
});

<div ng-app="invoice1" ng-controller="InvoiceController as invoice">
  <b>Invoice:</b>
  <div>
    Quantity: <input type="number" min="0" ng-model="invoice.qty" required >
  </div>
  <div>
    Costs: <input type="number" min="0" ng-model="invoice.cost" required >
    <select ng-model="invoice.inCurr">
      <option ng-repeat="c in invoice.currencies">{{c}}</option>
    </select>
  </div>

我不明白的是,這里的controller = model。 我不對嗎?

請了解控制器僅執行業務邏輯。

MVC-model views and controllers.

model:only the data

view:View is display of model that is your data.  only the visible part(html)

controller: which handles and manipulates the data.

模型是數據 ,而不是業務邏輯,而控制器負責處理它 也讀了這個

模型通常包含數據和與該數據直接相關的方法。 Controller將數據與視圖(以及Angular的服務等)連接起來。 Angular的控制器到底要做什么。 人們在模型或控制器上放置大量邏輯時,這是常見的做法。 以Angular的方式,還有很多其他包含邏輯的東西。 模型僅包含數據,而控制器僅用於將所有這些部分連接在一起。 仔細查看ng-model指令:實際上是綁定它以僅查看變量!

[稍后添加,示例添加到問題之后]呵呵! 那是個棘手的例子。 在其中,控制器實際上看起來像一個模型。 更好看這個例子

phonecatApp.controller('PhoneListCtrl', function ($scope) {
  $scope.phones = [
    {'name': 'Nexus S',
     'snippet': 'Fast just got faster with Nexus S.',
     'age': 1},
    {'name': 'Motorola XOOM™ with Wi-Fi',
     'snippet': 'The Next, Next Generation tablet.',
     'age': 2},
    {'name': 'MOTOROLA XOOM™',
     'snippet': 'The Next, Next Generation tablet.',
     'age': 3}
  ];

  $scope.orderProp = 'age';
});

這里controller是controller, phonesorderProp是模型, $scope是作用域。 =)看這張照片: 在此處輸入圖片說明 您會看到模型位於控制器范圍內。

MVC實際上只是模式。 您可以自由地以不同的神秘方式使用它,沒有關於錯誤模式使用的編譯器錯誤。 但是使用它的唯一原因-使內容更簡單。 因此,減少棘手的方法會更好!

Angular並不嚴格遵循MVC。 它更接近MVVM:Model-View-ViewModel(或Model-View-Whatever ,雖然不是很有幫助)。

簡而言之:

  • Angular Controller和Scope進入ViewModel層:

ViewModel可以看作是充當數據轉換器的專用控制器。 從這里開始 )。

它的職責是僅表示視圖所需的數據並將其粘貼到視圖。 通常從實際的Model層復制或引用此處的數據。

  • 模型層(在MVVM中)對視圖一無所知。 這是Angular Services的去向,也是您要運用大部分業務邏輯的地方,以使Angular Controller(即ViewModel層)變薄。

可悲的是,在各種教程中經常發生的一種典型的違反此模式的行為是將服務器請求放入Controller。 假設您要更改后端-現在您正在重寫Controller! 與您的后端對話的每一個人! 相反,您的控制器應該對服務器一無所知。 該信息進入您的模型(Angular Services)。 然后,對后端進行任何更改,您只需要重寫專門處理它的服務即可。 更清潔,更易於維護。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM