使用AngularJs将JSON数组值解析为文本字符串

时间:2015-04-11 10:31:23

标签: javascript json angularjs

我需要访问数组内的值" position"使用AngularJS的这个json文件。我的问题是我需要将它们作为文本字符串值,因为我需要在标记内添加它们作为css类名,基本上是这样的:

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

这是我的Json文件:

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

我无法弄清楚如何做到这一点。 提前感谢您的建议。

1 个答案:

答案 0 :(得分:3)

您只需join数组内的文字。

&#13;
&#13;
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"]
  }
];

});
&#13;
<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>
&#13;
&#13;
&#13;