如何在两个控制器中使用单个JSON对象而无需在angularjs中单独调用?

时间:2014-12-16 08:56:18

标签: angularjs

我有两页。一个是列表及其详细信息页面。页面的数据都来自单个json。我有两个控制器用于这两个页面。我想在一个调用的两个控制器中使用相同的json。 json结构是这样的:

[
  {
    "tid": "3388",
    "name": "Adagio Bar",
    "description": "Choose to enjoy one of our Italian inspired cocktails while taking in the spectacular views or simply 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 you on every voyage.
    "field_location_category": "Aft",
    "category_tid": "350",
    "category_name": "Food and Dining",
    "deck": "Fiesta Deck 6"
  }
 ]

当我们按下列表页面时,网址就像这样的“list / tid”
如何指出相应的清单详细信息?

控制器

'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");
        });
});

我在以下链接中为列表页面及其详细信息页面添加了html http://jsfiddle.net/cAY2N/14/

请帮忙。 提前谢谢。

2 个答案:

答案 0 :(得分:2)

正如@jao建议的那样,您可以创建一个返回承诺的工厂:

'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 the request.');
      });
    return deferred.promise;
  };

  return LocationService;
}]);

所以在你的控制器中你必须注入LocationService并调用它的方法get():

var promise = LocationService.get();
promise.then(function(data) {
    // do stuff
}, function() {
    console.log('An error occurred while processing the request.');
});

答案 1 :(得分:1)

@jao在评论中已经提到的正确答案。但是,可能还需要添加一个例子。基本思想是使用 singleton 对象来存储数据。可以使用工厂完成。两个控制器都可以引用此对象,并且只能填充一次。这是代码:

 var myApp = angular.module('myApp', []);

// define a singleton object to be used in conrollers
myApp.factory('LocationsData', function() {
    return {
        locations: [],
        current:undefined
    };
});        

function LocationsCtrl($timeout, $scope, LocationsData) {
    $scope.data = LocationsData;
    // perform asynch call, e.g using $http
    $timeout(function() {
        $scope.data.locations = ['First', 'Second'];
        $scope.data.current = $scope.data.locations[0];
    }, 1000);
}

function LocationDetailsCtrl($scope, LocationsData) {
    // just add to scope and wait to be populated
    $scope.data = LocationsData;
}

查看:

<div ng-controller="LocationsCtrl">
    <p>Locations List</p>
    <ul>
        <li ng-repeat="location in data.locations">{{location}}</li>
    </ul>
</div>

<div ng-controller="LocationDetailsCtrl">
    <p>Location Details</p>
    {{data.current}}
</div>

Link to JSFiddle