参考:http://docs.angularjs.org/tutorial/
创建Module
使用module()方法。在第2个参数中传入依赖模块数组。
var phonecatApp = angular.module(\'phonecatApp\', [ \'ngRoute\', \'phonecatControllers\' ]);
注册Controller
使用controller()方法。
NG识别参数名并自动注入依赖。若使用代码压缩,则参数名将被压缩从而无法使用自动注入。
使用以下两种显式注入方式可解决代码压缩带来的问题。
方式一、
function PhoneListCtrl($scope, $http) {...} PhoneListCtrl.$inject = [\'$scope\', \'$http\']; phonecatApp.controller(\'PhoneListCtrl\', PhoneListCtrl);
方式二、
function PhoneListCtrl($scope, $http) {...} phonecatApp.controller(\'PhoneListCtrl\', [\'$scope\', \'$http\', PhoneListCtrl]);
注册控制器时通常采用匿名函数的写法
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动作。
1、设置HTTP请求为GET方法。
2、指定url模板中的【phoneId】参数为【phones】。
3、返回值为数组。
使用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; }]);