前边讲的都是基础。本章看看他们怎么合作的。
我们要建一个程序。一次一步。章末结束
【这个程序】
GutHub是一个简单的菜谱管理程序。功能是存好吃的的菜谱并提供步骤。这个程序包含:
两列布局
左边是导航
允许你创建一个新的菜谱
能浏览已经存在的菜谱
主页面在右半部分。如下图
【模型控制器和页面模板的关系】
页面模板作用:
过滤数据
定义样式
定义用户交互
展示模型数据
视图是模板和模型的组合
【模型】
一个recipe包含如下属性
ID、名字、简短描述、做法指南、是不是特色菜、原料
如:
{
"id": "1",
"title": "Cookies",
"description": "Delicious, crisp on the outside, chewy" +
" on the outside, oozing with chocolatey goodness " +
"cookies. The best kind",
"ingredients": [
The Model | 79
{
"amount": "1",
"amountUnits": "packet",
"ingredientName": "Chips Ahoy"
}
],
"instructions": "1. Go buy a packet of Chips Ahoy\n" +
"2. Heat it up in an oven\n" +
"3. Enjoy warm cookies\n" +
"4. Learn how to bake cookies from somewhere else"
}
【控制器、指令和服务】
服务
// This file is app/scripts/services/services.js
var services = angular.module('guthub.services', ['ngResource']);
services.factory('Recipe', ['$resource',
function($resource) {
return $resource('/recipes/:id', {id: '@id'});
}]);
services.factory('MultiRecipeLoader', ['Recipe', '$q',
function(Recipe, $q) {
return function() {
var delay = $q.defer();
Recipe.query(function(recipes) {
delay.resolve(recipes);
}, function() {
delay.reject('Unable to fetch recipes');
});
return delay.promise;
};
}]);
services.factory('RecipeLoader', ['Recipe', '$route', '$q',
function(Recipe, $route, $q) {
return function() {
var delay = $q.defer();
Recipe.get({id: $route.current.params.recipeId}, function(recipe) {
delay.resolve(recipe);
}, function() {
delay.reject('Unable to fetch recipe ' + $route.current.params.recipeId);
});
return delay.promise;
};
}]);