用AngularJs解析JSON数组值到文本字符串

时间:2021-10-02 21:14:53

I need to access to the values inside the array "position" of this json file using AngularJS. My problem is that I need to get them as text string values, because I need to add them as css class name inside a tag, basically like this:

我需要使用AngularJS访问这个json文件的数组“position”中的值。我的问题是,我需要将它们作为文本字符串值来获取,因为我需要将它们作为css类名添加到标记中,基本上如下所示:

<div class="europe italy rome"></div>
<div class="europe france paris></div>
<div class="america usa atlanta></div>

This is my Json file:

这是我的Json文件:

 [
      {
        "name": "Rome",
        "position": ["europe", "italy", "rome"]
      },
      {
        "name": "Paris",
        "position": ["europe", "france", "paris"]
      },
      {
        "name": "Rome",
        "position": ["america", "usa", "atlanta"]
      }
]

I'm not able to figure it out how to do this. Thank you in advance for your suggestions.

我不知道怎么做。提前谢谢你的建议。

1 个解决方案

#1


3  

You can just join the text inside array.

你可以加入数组中的文本。

angular.module("app",[])
.controller("MainCtrl", function($scope) {
   $scope.styles = [
  {
"name": "Rome",
"position": ["europe", "italy", "rome"]
  },
  {
"name": "Paris",
"position": ["europe", "france", "paris"]
  },
  {
"name": "Rome",
"position": ["america", "usa", "atlanta"]
  }
];

});
<html ng-app="app">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body ng-controller="MainCtrl">

 <div ng-repeat="style in styles" ng-class="style.position.join(' ')">
   applied style : {{style.position.join(' ')}}
 </div>
</body>
</html>

#1


3  

You can just join the text inside array.

你可以加入数组中的文本。

angular.module("app",[])
.controller("MainCtrl", function($scope) {
   $scope.styles = [
  {
"name": "Rome",
"position": ["europe", "italy", "rome"]
  },
  {
"name": "Paris",
"position": ["europe", "france", "paris"]
  },
  {
"name": "Rome",
"position": ["america", "usa", "atlanta"]
  }
];

});
<html ng-app="app">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body ng-controller="MainCtrl">

 <div ng-repeat="style in styles" ng-class="style.position.join(' ')">
   applied style : {{style.position.join(' ')}}
 </div>
</body>
</html>