参考:http://docs.angularjs.org/tutorial/html
建立Moduleangularjs
使用module()方法。在第2个参数中传入依赖模块数组。json
var phonecatApp = angular.module('phonecatApp', [ 'ngRoute', 'phonecatControllers' ]);
注册Controller数组
使用controller()方法。ide
NG识别参数名并自动注入依赖。若使用代码压缩,则参数名将被压缩从而没法使用自动注入。函数
使用如下两种显式注入方式可解决代码压缩带来的问题。url
方式1、spa
function PhoneListCtrl($scope, $http) {...} PhoneListCtrl.$inject = ['$scope', '$http']; phonecatApp.controller('PhoneListCtrl', PhoneListCtrl);
方式2、翻译
function PhoneListCtrl($scope, $http) {...} phonecatApp.controller('PhoneListCtrl', ['$scope', '$http', PhoneListCtrl]);
注册控制器时一般采用匿名函数的写法code
phonecatApp.controller('PhoneListCtrl', ['$scope', '$http', function($scope, $http) {...}]);
使用$http模块进行HTTP请求
请求url为'phones/phones.json',并经过success方法设置请求成功后的回调函数。
NG将自动侦测JSON响应并解析。
$http.get('phones/phones.json').success(function(data) { $scope.phones = data; });
注册Service
注册服务,须要建立一个依赖于ngResource【angular-resource.js】的模块。
使用factory方法(除此以外还有provide()和service()方法),显式注入ngResource.$resource。
教程中没有对$resource解释得比较清楚,故而参考了在线文档,并翻译以下:
http://www.cnblogs.com/koukabatsugun/p/3442525.html
var phonecatServices = angular.module('phonecatServices', ['ngResource']); phonecatServices.factory('Phone', ['$resource', function($resource){ return $resource('phones/:phoneId.json', {}, { query: {method:'GET', params:{phoneId:'phones'}, isArray:true} }); }]);
以上,$resouce的第三个参数actions中,覆盖了默认的query动做。
一、设置HTTP请求为GET方法。
二、指定url模板中的【phoneId】参数为【phones】。
三、返回值为数组。
使用Phone服务的参考代码以下:
$scope.phones = Phone.query(); $scope.phone = Phone.get({phoneId: $routeParams.phoneId}, function(phone) { $scope.mainImageUrl = phone.images[0]; });
定义Router
为应用配置路由,须要建立一个依赖于ngRoute【angular-route.js】的模块。
使用模块的config()方法,显式注入ngRoute.$routeProvider。
var phonecatApp = angular.module('phonecatApp', [ 'ngRoute', 'phonecatControllers' ]); phonecatApp.config(['$routeProvider', function($routeProvider) { $routeProvider. when('/phones', { templateUrl: 'partials/phone-list.html', controller: 'PhoneListCtrl' }). when('/phones/:phoneId', { templateUrl: 'partials/phone-detail.html', controller: 'PhoneDetailCtrl' }). otherwise({ redirectTo: '/phones' }); }]);
从URL中获取参数
依赖$routeParams。
从【/phones/:phoneId】中获取phoneId,只需$routeParams.phoneId。
phonecatControllers.controller('PhoneDetailCtrl', ['$scope', '$routeParams', function($scope, $routeParams) { $scope.phoneId = $routeParams.phoneId; }]);