【发布时间】:2015-02-17 18:52:41
【问题描述】:
我有一个服务,它使用 $http 加载数据并返回一个承诺(为简洁起见):
angular.module('myApp').factory('DataService', ['$http', function($http) {
function unwrapFriendList(data) {
...
return unwrappedFriendList;
}
return {
getFriendList: function() {
return $http.get('/api/friends').then(unwrapFriendList);
}
}
}]);
这是一个使用该数据的视图,在 promise 被解析并将结果存储在 $scope.friends 之后:
<div ng-repeat='friend in friends'>
{{friend.firstName}} {{friend.lastName}}
</div>
在将数据加载到控制器时,我遇到了几种方法。
选项 1:使用通过 ng-route resolve 加载的数据的控制器
angular.module('myApp').controller('FriendListCtrl', ['$scope', 'friendList', function($scope, friendList) {
$scope.friends = friendList;
}]);
路线部分:
angular.module('myApp', ...).config(function($routeProvider) {
$routeProvider
.when('/friends', {
templateUrl: 'views/friends.html',
controller: 'FriendListCtrl',
resolve: {
friendList: ['DataService', function(DataService) {
return DataService.getFriendList();
}]
}
})
...
});
选项2:自行触发数据加载的控制器
angular.module('myApp').controller('FriendListCtrl', ['$scope', 'DataService', function($scope, DataService) {
DataService.getFriendList().then(function(friendList) {
$scope.friends = friendList;
});
}]);
问题
- 还有其他常用的方法吗?如果有,请用代码示例说明。
- 每种方法的局限性是什么?
- 每种方法的优势是什么?
- 在什么情况下应该使用每种方法?
【问题讨论】:
标签: angularjs angularjs-service angularjs-routing