Angularjs -- 基本概念
angularjs旨在減輕使用AJAX開發應用程式的複雜度,使得程式的建立、測試、擴充和維護變得容易。下面是angularjs中的一些核心概念。
1. 用戶端模板 多頁面的應用通過組裝和拼接伺服器上的資料來產生HTML,然後輸出到瀏覽器。Angularjs不同於此的是,傳遞模板和資料到瀏覽器,然後在瀏覽器端進行組裝。瀏覽器的角色編程了只提供模板的靜態資源和模板所需要的資料。
hello.html
<script src="angular.js"></script><script src="controllers.js"></script>{{greeting.text}}, World
|
controllers.js
function HelloController($scope) { $scope.greeting = { text: 'Hello' };} |
2. 模型 視圖 控制器(MVC) MVC的核心概念是,在代碼之間明確分離管理資料(模型),應程式邏輯(控制器),並將資料呈現給使用者(視圖)。在Angular應用中,視圖就是DOM,控制器就是Javascript類,模型資料存放區在對象屬性中。
3. 資料繫結 典型的DOM操作,都是先將資料處理完畢之後,再通過元素上設定innerHTML將結果插入到所要的DOM中。這樣的工作重複性很高,還要確保介面和javascript屬性中擷取到資料時正確的狀態。 而Angular中包括這中功能,僅僅聲明介面的某一部分銀蛇到Javascript的屬性,讓它們自動完成同步。
<script src="angular.js"></script><script src="controllers.js"></script>{{greeting.text}}, World
|
controllers.jsfunction HelloController($scope) { $scope.greeting = { text: 'Hello' };} |
input的值(使用者的輸入)與greeting.text綁定在一起,並及時呈現在
中。綁定是雙向的,也可用通過設定$scope.greeting.text的值,並自動同步到輸入框和雙大括弧({{}})中
4. 依賴注入 $scope對象吧資料繫結自動通過HelloController建構函式傳遞給開發人員,$scope並不是我們唯一需要的,還可以添加一個$location對象,如:
function HelloController($scope, $location) {$scope.greeting = { text: 'Hello' };// use $location for something good here...} |
通過Angular的依賴注入系統,我們能夠遵循迪米特法則(最少知識原則),只關注我們最需要的部分。
5. 指令 Angular包括一個強大的DOM轉換引擎,使得開發人員有能力擴充HTML文法。在之前的執行個體中我們看到{{}}是用綁定資料的,ng-controller是用來指定哪個控制器來服務哪個視圖,ng-model將一個輸入框綁定到模型部分。我們稱之為HTML擴充指令。 Angular包含很多標識符來定義視圖,這些標識符可以定義常見的視圖作為模板。除此之外,開發人員還可以編寫自己的標識符來擴充HTML模板。
購物車樣本:
Your Shopping CartYour Order Remove<script src="../js/angular-1.2.2/angular.js"></script><script> function CartController($scope) { $scope.items = [ {title: 'Paint pots', quantity: 8, price: 3.95}, {title: 'Polka dots', quantity: 17, price: 12.95}, {title: 'Pebbles', quantity: 5, price: 6.95} ]; $scope.remove = function (index) { $scope.items.splice(index, 1); } }</script> |
ng-app告訴Angular管理頁面的那一部分。根據需要ng-app也可以放在上
Javascript類叫做控制器,它可以管理相應頁面地區中的任何東西。
ng-repeat代表為items數組中每個元素拷貝一次該DIV中的DOM,同時設定item作為當前元素,並可在模板中使用它。 {{item.title}} 運算式{{item.title}}檢索迭代中的當前項,並將當前項的title屬性值插入到DOM中
ng-model定義輸入欄位和item.quantity之間的資料繫結 {{item.price | currency}} {{item.price * item.quantity | currency}} 單價和總價格式化成美元形式。通過Angular的currency過濾器進行美元形式的格式化。 Remove 通過ng-repeat的迭代順序$index,移除資料和相應的DOM(雙向繫結特性) function CartController($scope) { CartController 管理這購物車的邏輯,$scope 就是用來把資料繫結到介面上的元素 $scope.items = [ {title: 'Paint pots', quantity: 8, price: 3.95}, {title: 'Polka dots', quantity: 17, price: 12.95}, {title: 'Pebbles', quantity: 5, price: 6.95} ]; 通過定義$scope.items,我們已經建立一個虛擬資料代表了使用者購物車中物品集合,購物車是不能僅工作在記憶體中,也需要通知伺服器端持久化資料。 $scope.remove = function(index) {$scope.items.splice(index, 1);}; remove()函數能夠綁定到介面上,因此我們也把它增加到$scope 中 |