05.15 Angular初探----UI邏輯Controller

Angular初探----UI邏輯Controller

在前面示例基礎上,我們添加內容實現用戶可以選擇不同的貨幣計算支付收據的費用。

Invoice:
Quantity:
Costs: <select> <option>{{c}}/<option> /<select>
Total: {{invoice.total(c) | currency:c}} <button>Pay/<button>

angular.module('invoice1', [])

.controller('InvoiceController', function() {

this.qty = 1;

this.cost = 2;

this.inCurr = 'EUR';

this.currencies = ['USD', 'EUR', 'CNY'];

this.usdToForeignRates = {

USD: 1,

EUR: 0.74,

CNY: 6.09

};

this.total = function total(outCurr) {

return this.convertCurrency(this.qty * this.cost, this.inCurr, outCurr);

};

this.convertCurrency = function convertCurrency(amount, inCurr, outCurr) {

return amount * this.usdToForeignRates[outCurr] / this.usdToForeignRates[inCurr];

};

this.pay = function pay() {

window.alert("Thanks!");

};

});

首先、有一點新的JavaScript文件(invoice1.js如上)我們稱之為控制器(Controller)。文件包含了結構化的JavaScript函數,以此創建實際的控制器實體類。控制器的目的就是將變量和函數暴露給表達式和指令使用。

在新文件中包含了控制器,我們也可以注意到添加了ng-controller指令。這個指令告訴Angular,新的InvoiceController控制器是為指令所在的標籤以及子標籤服務的。InvoiceController as invoice控制器的語法就是初始化一個控制器並保存到變量invoice中。

只要頁面所有的表達式以invoice為前綴,我們就可以改變控制器中所有表達式邏輯讀取改變變量的值。在控制器中列舉出所有可能的貨幣形式,在模板中添加ng-repeat指令。

綁定是動態的綁定。無論合適結果發生改變,DOM操作會自動變化。付款的按鈕使用了指令ngClick,點擊時它將鏈接相應的表達式。

在新文件中我們創建了模塊(Module)並註冊了一個控制器。

譯文地址:http://docs.angularjs.cn/guide/concepts


分享到:


相關文章: