通过Angular中生成的字符串访问JSON对象

时间:2021-10-02 15:55:38

I am creating a controller in Angular for which I get the url parts and some parameters with $statePrams.

我正在Angular中创建一个控制器,我可以通过$ statePrams获取url部分和一些参数。

I call the $http service to get data back from a json file. After getting the data back, I assign the specified object element's content -which specification is generated from $stateParams- to a $scope variable which I can process in my view to generate some kind of unordered list elements.

我调用$ http服务从json文件中获取数据。在获取数据之后,我将指定的对象元素的内容(从$ stateParams-生成的规范)分配给$ scope变量,我可以在视图中处理该变量以生成某种无序列表元素。

My problem is when I generate for example the path as result['data']['datas']['timeline'] , then it won't work, and give me ngRepeat:dupe error.

我的问题是当我生成例如结果['data'] ['datas'] ['timeline']的路径时,它将无法工作,并给我ngRepeat:dupe错误。

However there are no duplicates at all. If I just type it in manually like $scope.naviData = result['data']['datas']['timeline']; , it will generate the object, give me all the needed data and draw the li elements in the view.

但是根本没有重复。如果我只是手动输入,如$ scope.naviData = result ['data'] ['datas'] ['timeline']; ,它将生成对象,给我所有需要的数据并在视图中绘制li元素。

How could I solve this problem since I do not know how to do this dynamic object element access otherwise. Here are two images:

我怎么能解决这个问题,因为我不知道如何做这个动态对象元素访问。这是两张图片:

First one is with manual writing 通过Angular中生成的字符串访问JSON对象

第一个是手动编写

Second one is with dynamically generated variable 通过Angular中生成的字符串访问JSON对象 The first console.info in both case are the state params I generate the path from. Also here are the codes doing the magic part for me.

第二个是动态生成的变量。在这两种情况下,第一个console.info是我生成路径的状态参数。这里还有代码为我做了神奇的部分。

angular.module('MPWeb.datas', [])
  .controller('DataDetailsCtrl', function($scope, $state, $stateParams, $http) {
    $scope.params = $stateParams;
    // set datas for dynamic object handling
    var base = 'data.datas';
    var category = ($scope.params.categoryId) ? $scope.params.categoryId : '';
    var article = ($scope.params.articleId) ? $scope.params.articleId : '';
    var stateConfig = (article) ? {
      params: {
        prefix: base,
        categoryId: category,
        articleId: article
      }
    } : {
      params: {
        prefix: base,
        categoryId: category
      }
    };
    console.info(stateConfig.params); // this is the first console entry on the screenshots
    // with this function I get back a standard joined string
    var objToString = function(obj) {
      var tabjson = [];
      for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
          tabjson.push(obj[p]);
        }
      }
      tabjson.push()
      return tabjson.join('.');
    };
    // generate sideNavigation
    $http({
      method: 'GET',
      url: './json/mp-navigation.json'
    }).then(function successCallback(result, status, headers) {
      var temp = objToString(stateConfig.params);
      var naviTemp = (stateConfig.params.articleId) ? temp.replace(/\.[^.]+$/, "") : temp;
      naviTemp = "result['" + naviTemp + "']";
      naviTemp = naviTemp.replace(/\./g, "']['"); // dynamically generated path with bracket notation method
      //$scope.naviData = naviTemp; // if I use this, it gives me the error
      $scope.naviData = result['data']['datas']['timeline'];
      console.info(naviTemp);
    }, function errorCallback(result, status, headers) {
      console.warn(status);
    });
  });

Also if I use track by $index in my view it will just generate li elements from the letters of my generated path.

另外,如果我在视图中使用$ index跟踪,它只会从生成的路径的字母中生成li元素。

2 个解决方案

#1


0  

The Problem is you have used trackby in your ng-repeat in your template. but the trackby accepts unique keys from the objects in array .

问题是您在模板中的ng-repeat中使用了trackby。但是trackby接受来自数组中对象的唯一键。

ex :

values = [{id:12,name:'king'},{id:13:name :'ram'},{id:14:name:'king'}]

Correct

<div ng-repeat="value in values  track by id">
{{value.name}} : {{value.id}}
</div>

Correct

<div ng-repeat="value in values  track by $index">
{{value.name}} : {{value.id}}
</div>

Wrong because name is not unique

错了,因为名字不是唯一的

<div ng-repeat="value in values  track by name">
{{value.name}} : {{value.id}}
</div>

#2


0  

So after some days, I finally figured it out with a little help. For anybody who find this issue in the future, this is how to solve in the controller:

所以过了几天,我终于想出了一点帮助。对于将来发现此问题的任何人,这是如何在控制器中解决:

  $scope.params = $stateParams;
  $scope.navPrefix = $state.current.url.split('/:')[0];
  $scope.navPrefix = ($scope.params.categoryId) ? $scope.navPrefix + '/' + $scope.params.categoryId + '/' : $scope.navPrefix + '/';
  $scope.activeItem = ($scope.params.articleId) ? $scope.params.articleId : $scope.params.categoryId;
  var tempCat = $state.current.url.substr(1);
  $scope.naviCat = tempCat.split('/:')[0];
  // set datas for dynamic object handling
  var base = $scope.naviCat;
  ...
  // generate sideNavigation
  $http({
    method: 'GET',
    url: './json/mp-navigation.json'
  }).then(function successCallback(result, status, headers) {
    var naviMain = result.data[$scope.naviCat]['main'];
    var naviTemp = result.data[stateConfig.params.prefix][stateConfig.params.categoryId];
    $scope.naviData = (stateConfig.params.categoryId == '') ? naviMain : naviTemp;
    }, function errorCallback(result, status, headers) {
      console.warn(status + ' with getting: ' + headers);
  });

Cheers

#1


0  

The Problem is you have used trackby in your ng-repeat in your template. but the trackby accepts unique keys from the objects in array .

问题是您在模板中的ng-repeat中使用了trackby。但是trackby接受来自数组中对象的唯一键。

ex :

values = [{id:12,name:'king'},{id:13:name :'ram'},{id:14:name:'king'}]

Correct

<div ng-repeat="value in values  track by id">
{{value.name}} : {{value.id}}
</div>

Correct

<div ng-repeat="value in values  track by $index">
{{value.name}} : {{value.id}}
</div>

Wrong because name is not unique

错了,因为名字不是唯一的

<div ng-repeat="value in values  track by name">
{{value.name}} : {{value.id}}
</div>

#2


0  

So after some days, I finally figured it out with a little help. For anybody who find this issue in the future, this is how to solve in the controller:

所以过了几天,我终于想出了一点帮助。对于将来发现此问题的任何人,这是如何在控制器中解决:

  $scope.params = $stateParams;
  $scope.navPrefix = $state.current.url.split('/:')[0];
  $scope.navPrefix = ($scope.params.categoryId) ? $scope.navPrefix + '/' + $scope.params.categoryId + '/' : $scope.navPrefix + '/';
  $scope.activeItem = ($scope.params.articleId) ? $scope.params.articleId : $scope.params.categoryId;
  var tempCat = $state.current.url.substr(1);
  $scope.naviCat = tempCat.split('/:')[0];
  // set datas for dynamic object handling
  var base = $scope.naviCat;
  ...
  // generate sideNavigation
  $http({
    method: 'GET',
    url: './json/mp-navigation.json'
  }).then(function successCallback(result, status, headers) {
    var naviMain = result.data[$scope.naviCat]['main'];
    var naviTemp = result.data[stateConfig.params.prefix][stateConfig.params.categoryId];
    $scope.naviData = (stateConfig.params.categoryId == '') ? naviMain : naviTemp;
    }, function errorCallback(result, status, headers) {
      console.warn(status + ' with getting: ' + headers);
  });

Cheers