前边讲的都是基础。本章看看他们怎么合做的。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 }
【控制器、指令和服务】
服务
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 }]);