I have a service which looks likes the following:
var chatServices = angular.module('chatServices', ['ngResource']);
chatServices.factory('Chat',['$resource',
function($resource){
return $resource('sample-chat-data.json', {}, {
query: {method:'GET', params:{}, isArray:true}
});
}
]);
I have two controllers, one for the main and one for the detailed view:
chatListApp.controller('ChatItemsController', ['$scope', 'Chat', "$location",
function ($scope, Chat, $location) {
$scope.chatitems = Chat.query();
$scope.detailPage = function (hash) {
$location.path(hash);
}
}]);
chatListApp.controller('ChatDetailController', ['$scope', "$routeParams", "Chat",
function ($scope, $routeParams, Chat) {
$scope.chatID = $routeParams.chatID;
$scope.chatitems = Chat.query(function() {
for (var i = 0; i < $scope.chatitems.length; i++) {
if ($scope.chatitems[i].id === $scope.chatID) {
$scope.chat = $scope.chatitems[i];
break;
}
};
});
}]);
I have a feeling that my code is far from optimal, and the reason is I am doing the same query, two times. Is there a smart way to do this? Can I somehow save/cache the result of my service to a variable?
You can see the full code and an online working example of the SPA there: https://github.com/gkatsanos/angular-demo
turn on your cache
chatServices.factory('Chat',['$resource',
function($resource){
return $resource('sample-chat-data.json', {}, {
query: {method:'GET', params:{}, isArray:true,cache : true}
});
}
]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.