angular.js从数组中获取特定值

时间:2016-03-12 12:37:02

标签: javascript jquery angularjs

我想在角度js中检索多维对象中的特定值。 我的目标是这样的:

 $Item =   [{item1: 'lorem ipsum'}, {item2: [{inner_item:'lorem ipsum', inner_item2: 'lorem ipsum'}]},...]

如何通过在jquery中指出来在控制器中实现这一点:

$Item[1][2];
and also in the expression 
{{???}}

2 个答案:

答案 0 :(得分:1)

您的数据有点含糊不清但我会告诉您如何以正确的Angular方式进行两种变化:

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

app.controller('TestCtrl', ['$scope', function($scope) {
  $scope.items =  [{country: 'Germany'}, 
                   {country: 'Spain'}, 
                   {country: 'England'}];
  $scope.nestedItems = [{continent: 'Europe', 
                         countries: [
                           {country: 'Germany'}, 
                           {country: 'Spain'}, 
                           {country: 'England'}]
                        }];
}]);
.single {
    background-color: lightgreen;
}

.nested {
    background-color: lightblue;  
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">

</script>
<section ng-app="myApp" ng-controller="TestCtrl">
  <div class="single">
   <ul>
    <li ng-repeat="item in items"> 
      Country: {{item.country}}
    </li>
  </ul>
  </div>
  <div class="nested" ng-repeat="item in nestedItems">
    <h2>Continent: {{item.continent}}</h2>
    <ul>
    <li ng-repeat="item in item.countries"> 
      Country: {{item.country}}
    </li>
  </ul>
  </div>
  
  
</section>

答案 1 :(得分:0)

  • 数组项目可以通过方形表示法访问(例如:item[0]
  • 对象参数可以通过点符号访问(例如:item1.paramater

var app = angular.module('app', []).controller('indexCtrl', function ($scope) {
    $scope.item = [
      {item1: 'lorem ipsum'},
      {item2: [{inner_item:'lorem ipsum', inner_item2: 'lorem ipsum'}]
      }];  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="indexCtrl">
  <p>item[0]: {{item[0]}}</p>
  <p>item[0].item1: {{item[0].item1}}</p>
  <p>item[1]: {{item[1]}}</p>
  <p>item[1].item2[0]: {{item[1].item2[0]}}</p>
  <p>item[1].item2[0].inner_item: {{item[1].item2[0].inner_item}}</p>
</div>