[AngularJS]Chapter 4 AngularJS程序案例分析

前邊講的都是基礎。本章看看他們怎麼合做的。promise

咱們要建一個程序。一次一步。章末結束cookie

【這個程序】app

GutHub是一個簡單的菜譜管理程序。功能是存好吃的的菜譜並提供步驟。這個程序包含:ide

  兩列布局佈局

  左邊是導航fetch

  容許你建立一個新的菜譜spa

  能瀏覽已經存在的菜譜code

主頁面在右半部分。以下圖blog

 

【模型控制器和頁面模板的關係】ip

頁面模板做用:

  過濾數據

  定義樣式

  定義用戶交互

  展現模型數據

視圖是模板和模型的組合

【模型】

一個recipe包含以下屬性

  ID、名字、簡短描述、作法指南、是否是特點菜、原料

如:

 1 {
 2 "id": "1",
 3 "title": "Cookies",
 4 "description": "Delicious, crisp on the outside, chewy" +
 5 " on the outside, oozing with chocolatey goodness " +
 6 "cookies. The best kind",
 7 "ingredients": [
 8 The Model  |  79
 9 {
10 "amount": "1",
11 "amountUnits": "packet",
12 "ingredientName": "Chips Ahoy"
13 }
14 ],
15 "instructions": "1. Go buy a packet of Chips Ahoy\n" +
16 "2. Heat it up in an oven\n" +
17 "3. Enjoy warm cookies\n" +
18 "4. Learn how to bake cookies from somewhere else"
19 }
View Code

【控制器、指令和服務】
服務

 1 // This file is app/scripts/services/services.js
 2 var services = angular.module('guthub.services', ['ngResource']);
 3 services.factory('Recipe', ['$resource',
 4 function($resource) {
 5 return $resource('/recipes/:id', {id: '@id'});
 6 }]);
 7 services.factory('MultiRecipeLoader', ['Recipe', '$q',
 8 function(Recipe, $q) {
 9 return function() {
10 var delay = $q.defer();
11 Recipe.query(function(recipes) {
12 delay.resolve(recipes);
13 }, function() {
14 delay.reject('Unable to fetch recipes');
15 });
16 return delay.promise;
17 };
18 }]);
19 services.factory('RecipeLoader', ['Recipe', '$route', '$q',
20 function(Recipe, $route, $q) {
21 return function() {
22 var delay = $q.defer();
23 Recipe.get({id: $route.current.params.recipeId}, function(recipe) {
24 delay.resolve(recipe);
25 }, function() {
26 delay.reject('Unable to fetch recipe '  + $route.current.params.recipeId);
27 });
28 return delay.promise;
29 };
30 }]);
View Code
相關文章
相關標籤/搜索