如何在Angular中动态获取JSON变量的值?

时间:2016-08-23 22:58:12

标签: angularjs

您好,我想这样做:

{{item.price.{{comparator}}}}

我的意思是,使用{{comparator}}变量从价格类型中获取值。

这是我的代码示例(数据更大,价格更多):

var items = [
  {"name":"Item1",price:{public:10,private:15,other1:16.3,other2:17.5}},
  {"name":"Item2",price:{public:20,private:45}},
]
  
var angularApp = angular.module('angularApp', [
    'angularAppControllers',
]);

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


angularAppControllers.controller('ComparationCtrl', ['$scope',
    function ($scope) {
      $scope.comparator = "private";
      
      $scope.data = items;
    }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div ng-App="angularApp">
<div ng-controller="ComparationCtrl">
  <select ng-model="comparator">
    <option value="public">Public</option>
    <option value="private">Private</option>
    <option value="other1">Other 1</option>
    <option value="other2">Other 2</option>
    <option value="othern">....</option>
  </select>
  {{comparator}}
  <br />
  <ul>
    <li ng-repeat="item in data">
        {{item.name}} - {{item.price.public}} - <strong>(item.price.{{comparator}})</strong>
    </li>
</ul>
</div>
</div>

2 个答案:

答案 0 :(得分:2)

假设您的$ scope中定义了item.pricecomparator,请尝试:

{{ item.price[comparator] }}

答案 1 :(得分:0)

像这样:https://plnkr.co/edit/IrheJrHz8eOfb5LmTx7x

angular.module('app', [])
  .config(function() {

  })
  .controller('ctrl', function($scope) {
    $scope.obj = {
      "name": "Item1",
      "price": {
        "public": "10",
        "private": "15",
        "other1": "16.3",
        "other2": "17.5"
      }
    };
    $scope.prop = 'public';
});

HTML:

<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://code.angularjs.org/1.5.8/angular.js"></script>
  <link rel="stylesheet" href="style.css">
</head>

<body ng-controller="ctrl">
  <pre>{{obj.price[prop]|json}}</pre>
  <script src="script.js"></script>
</body>

</html>

基本上,{{obj [aPropertyDefinedInScope]}}