How to use a single JSON object in two controller without seperate call in angularjs? -
i have 2 pages. 1 list , detail page. both page’s data coming single json. have 2 controllers both pages. want use same json in 2 controllers single call. json structure this:
[ { "tid": "3388", "name": "adagio bar", "description": "choose enjoy 1 of our italian inspired cocktails while taking in spectacular views or relax. "field_location_category": "aft", "category_tid": "351", "category_name": "entertainment/bars", "deck": "sun deck 16" }, { "tid": "3439", "name": "botticelli dining room", "description": "a sumptuous variety of dining options awaits on every voyage. "field_location_category": "aft", "category_tid": "350", "category_name": "food , dining", "deck": "fiesta deck 6" } ]
when press list page url “list/tid”
how point out corresponding list details?
controller
'use strict'; var app = angular.module('location', []); app.controller("location", function($scope, $http){<br/> $scope.locationlist = null; $http.get("sites/all/modules/custom/locations/location.json") .success(function(data){ $scope.locationlist = data; var indexedloc = []; $scope.locationlisttofilter = function(){ indexedloc = []; return $scope.locationlist; } $scope.filterlocation = function(loc){ var locationisnew = indexedloc.indexof(loc.category_name) == -1; if(locationisnew){ indexedloc.push(loc.category_name); } return locationisnew; } $scope.returnfilterloc = function(){return indexedloc}; }) .error(function(data) { $("div.content").html("error"); }); });<br/> app.controller("locationdetail", function($scope, $http){ $scope.locationdetail = null; $http.get("sites/all/modules/custom/locations/location.json") .success(function(data){ $scope.locationdetail = data; })<br/> .error(function(data) { $("div.content").html("error"); }); });
i have added html list page , detail page in following link http://jsfiddle.net/cay2n/14/
please help. in advance.
as @jao suggested, create factory returns promise:
'use strict'; angular.factory('locationservice', ['$q', '$http', function($q, $http) { var locationservice = {}; locationservice.get = function(){ var deferred = $q.defer(); $http.get("sites/all/modules/custom/locations/location.json") .success(function(data) { deferred.resolve(data); }) .error(function() { deferred.reject('an error occured while processing request.'); }); return deferred.promise; }; return locationservice; }]);
so in controller have inject locationservice , call it's method get():
var promise = locationservice.get(); promise.then(function(data) { // stuff }, function() { console.log('an error occurred while processing request.'); });
Comments
Post a Comment