Angular和json - 从json获取值而不是硬编码的正确方法

时间:2015-09-26 14:43:14

标签: arrays json angularjs

替换从json获得的值的正确方法是什么

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

app.factory('myData', ['$http', function($http) {
  return {
    get: function() {
      return $http.get('data.json').then(function(response) {
        return response.data;
      });
    }
  };
}]);



app.controller('MainCtrl', ['$scope', '$http', 'myData', function($scope, $http, myData) {
  myData.get().then(function(data) {
    $scope.data = data; //this is fine
    $scope.Monday= Object.keys($scope.data.day.weekday.Monday.mac_id)
    $scope.Tuesday= Object.keys($scope.data.day.weekday.Tuesday.mac_id)
    $scope.Wednesday= Object.keys($scope.data.day.weekday.Wednesday.mac_id)
    console.log($scope.data );
  });
}]);

我想显示从json获得的macid的所有键,我使用了Object.keys($ scope.data.day.weekday.Monday.mac_id)

有没有更好的方法来获取数据,而不是分别在星期一,星期二,星期三等分析数据。 我相信我的工作方式并不有效

我的plunker链接http://plnkr.co/edit/9P9oGgLCuSgivmvbNN2e?p=preview

提前致谢

感谢任何帮助

2 个答案:

答案 0 :(得分:1)

有几个选择:

选项1:ng-repeat对象 weekData

假设在你的模型中,整周的数据在一个对象中:

$scope.weekData = $scope.data.day.weekday;

然后,您将迭代周数据:

<div ng-repeat="(day, valueForDay) in weekData">
    <ul ng-repeat="(key, macIds) in valueForDay">
      <li ng-repeat="(macKey, macVal) in macIds">{{macKey}}</li>
    </ul>
</div>

参见 plunker

选项2:在模型中转换数据

您可以转换模型中的数据,以便本周的所有mac_id值在结构中处于同一级别。这是一个示例算法:

myData.get().then(function(data) {
    var weekData = data.day.weekday,
        weekArrayData = [];
    Object.keys(weekData).forEach(function (day) {
        weekArrayData.push(weekData[day].mac_id);
    })
    $scope.weekArrayData = weekArrayData;
});

参见 plunker

答案 1 :(得分:0)

您可以像这样构建一个哈希:

app.controller('MainCtrl', ['$scope', '$http', 'myData', function($scope, $http, myData) {
  myData.get().then(function(data) {
    $scope.data = data; //this is fine
    $scope.output = [];
    for(var i=0; i<Object.keys(data.day.weekday).length; i++) {
      day = Object.keys(data.day.weekday)[i];
      keys = Object.keys(data.day.weekday[day].mac_id);
      $scope.output[day] = keys;
    }
 });
}]);

然后迭代哈希键。这是Plunker