决定将其表达为答案,因为在评论中我们基本上得出了您想知道的内容:
使用$ http或$ resource仍然可以缓存结果,您指出了在问题中真正使用一个结果的原因。如果您具有RESTful接口,那么使用$
resource会更好,因为最终您将编写更少的RESTful接口通用的样板代码,如果您不使用RESTful服务,则$
http更有意义。您可以使用以下两种方法之一来缓存数据:http://www.pseudobry.com/power-up-http-with-
caching/
我认为将$ http或$
resource请求放入服务通常效果更好,因为您希望从多个位置访问数据,并且该服务充当一个单例对象。因此,基本上,您可以在此处处理任何类型的缓存,并且控制器都可以仅监视适当的服务来更新自己的数据。我发现控制器中的$
watch组合用于获取服务上的数据,并从服务的方法中返回承诺,这使我在如何更新控制器中的内容方面具有最大的灵活性。
我将这样的东西放入控制器中,并将exampleService注入到控制器定义的顶部。
angular.module("exampleApp", []).service('exampleService', ["$http", "$q" ,function ($http, $q) { var service = { returneddata: [], dataLoaded:{}, getData = function(forceRefresh) { var deferred = $q.defer(); if(!service.dataLoaded.genericData || forceRefresh) { $http.get("php/getSomeData.php").success(function(data){ //service.returnedData = data; //As Mark mentions in the comments below the line above could be replaced by angular.copy(data, service.returnedData); //if the intention of the watch is just to update the data //in which case the watch is unnecessary and data can //be passed directly from the service to the controller service.dataLoaded.genericData = true; deferred.resolve(service.returnedData); }); } else { deferred.resolve(service.returnedData); } return deferred.promise; }, addSomedata:function(someDataToAdd) { $http.post("php/addSomeData.php", someDataToAdd).success(function(data){ service.getData(true); }); } }; service.getData(); return service;}]).controller("ExampleCtrl", ["$scope", "exampleService", function($scope, exampleService){ //$scope.$watch(function() {return exampleService.returnedData}, function(returnedData){ // $scope.myModel.someData = returnedData; //}); //if not using angular.copy() in service just use watch above $scope.myModel.someData = exampleService.returnedData;}]);另外,这是Angular团队关于“最佳做法”的精彩视频,我仍在重新观看,并逐渐吸收。



