ng-options循环遍历对象中的对象数组?

时间:2017-04-12 13:07:57

标签: javascript html ng-options

我有这种对象格式

{
      first_name : "Bob",
      last_name : "Smith",
      addresses : [
        {address:"1 Baker Street",
          city: "london"
        },
        {address:"2 Baker Street",
          city: "london"
        }
        ]
    }

我想在选择下拉列表中设置地址位,即" 1 Baker Street"," 2 Baker Street",

这是我的代码

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<select ng-model="selectedAddress" ng-options="item for item in testObject">
</select>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.testObject =     {
          first_name : "Bob",
          last_name : "Smith",
          addresses : [
            {address:"1 Baker Street",
              city: "london"
            },
            {address:"2 Baker Street",
              city: "london"
            }
            ]
        }
});
</script>

</body>
</html>

我正在努力探索如何使用AngularJS遍历对象。有什么帮助吗?

2 个答案:

答案 0 :(得分:4)

您必须调用数组的子对象和属性。看看这段代码。

&#13;
&#13;
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.testObject =     {
          first_name : "Bob",
          last_name : "Smith",
          addresses : [
            {address:"1 Baker Street",
              city: "london"
            },
            {address:"2 Baker Street",
              city: "london"
            }
            ]
        }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">

<select ng-model="selectedAddress" ng-options="item.address for item in testObject.addresses">
</select>

</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

检查一下:

 <select ng-model="selectedItem" 
         ng-options="selectedItem as selectedItem.address       
                     for selectedItem in testObject.addresses">  
</select>

您还可以将默认selectedItem设置为列表中的第1项

$scope.selectedItem = $scope.testObject.addresses[0];

Demo