AngularJS - 按ID获取数据

时间:2013-01-01 14:03:50

标签: controller get routes angularjs

我遇到以下情况:
我有一些自定义标记和静态(非谷歌)地图。我使用以下代码显示(并过滤)标记:

<div ng-controller="DealerDetailsListCtrl">
    <a ng-click="showdetails=!showdetails" href="#/dealer/{{marker.id}}" class="marker" style="left:{{marker.left}};top:{{marker.top}}" ng-repeat="marker in dealer|zipFilter:zipCodeLookup:countryLookup"></a>
</div>  

我将其路由到“dealer-details.html”,在那里我成功显示了ID:

  <div class="alldealermodal" ng-controller="DealerDetailsCtrl">      
    <div ng-view></div>
  </div>  

使用此控制器/路由:

app.config(['$routeProvider', function($routeProvider) {
  $routeProvider.
      when('/dealer/:id', {templateUrl: 'files/tpl/dealer-details.html', controller: DealerDetailsCtrl}).
      otherwise({redirectTo: '/'});
}]);  

function DealerDetailsCtrl($scope, $routeParams) {
  $scope.id = $routeParams.id;
}  

由于我对angularJS很新,我想知道,我怎么能通过ID获取所有数据。

我的json文件如下所示:

[
{
    "id": "2",

    "name": "Laden Dortmund",
    "strasse": "Unionstr.",
    "hausnr": 1,
    "plz": "45525",
    "stadt": "Dortmund",
    "land": "DE",
    "url": "http://www.google.de",
    "tel": "0234-234568",
    "email": "lade@indortmund.de",
    "left": "200px",
    "top": "300px",
    "lowRange":60000,
    "highRange":70000
},
{
    "id": "1",
    "name": "Laden Unna",
    "strasse": "Berlinerstr.",
    "hausnr": 134,
    "plz": "78654",
    "stadt": "Unna",
    "land": "AT",
    "url": "http://www.bing.de",
    "tel": "0234-11223344",
    "email": "lade@inunna.de",
    "left": "250px",
    "top": "500px",
    "lowRange":40000,
    "highRange":50000
}
]

依此类推....我想从所选的id中获取所有数据。我怎样才能做到这一点?有人会给你一个暗示吗?

我使用此控制器从json获取所有数据:

function DealerListCtrl($scope, $http) {
  $scope.dealer = [];
  $http.get('files/js/dealer.json').success(function(data) {
    $scope.dealerall = data;
  });
  $scope.orderProp = 'id';
}

1 个答案:

答案 0 :(得分:5)

首先,您无需在ng-controller="DealerDetailsCtrl"中设置dealer-details.html,因为ng-view会处理此问题。

其次,您应该提供service来检索您的数据:

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

app.factory('dealerService', function($http) {
   return {
      getDealerList function() {
         var dealers = {
            list : []
         };
         // TODO add possible caching via $cacheFactory
         $http.get('files/js/dealer.json').success(function(data) {
            dealers.list = data;
         });
         return dealers;
      },

      // other functions
   };

});

在您需要访问经销商的控制器中,只需注入DealerService,就像其他服务一样。要获取特定条目,只需迭代。

另一种可能性是使用$routeProvider上的resolve属性将经销商数据发送到DetailController。