ng-options loop through an array of objects within an object?

ぃ、小莉子 提交于 2019-12-25 05:23:44

问题


I have this object format

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

I want to set the address bits in the select dropdown i.e. "1 Baker Street", "2 Baker Street",

This is my code

<!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>

I'm struggling to get my head around how to loop through the objects with AngularJS. Any help?


回答1:


You have to call the child object of array and the property. Take a look this code.

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 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>



回答2:


Check this one:

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

You can also set default selectedItem as 1st item in list

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

Demo



来源:https://stackoverflow.com/questions/43370479/ng-options-loop-through-an-array-of-objects-within-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!