循环访问 Angularjs 中的 ng-options



我正在尝试使用 Angularjs 中的 ng-options 在选择框中推送一个值数组。

车把:

<div class="col-md-8">
    <select ng-options="item as item.label for item in items track by 
    item.id" ng-model="selected">
        <option></option>
    </select>
</div>

控制器:

var app = angular.module('myapp', []);
app.controller('mycontroller', function($scope) {
$scope.arealistArray=[];
$scope.items=[]; 
for(j=1;j<3;j++){
    $scope.arealistArray.push([{id: 'id'+j,label: 'aLabel'+j,subItem: { 
    name: 'aSubItem'+j }}]);
} 
$scope.items = $scope.arealistArray;

我的选项正在选择框中追加,但未为追加的选项定义标签。在 ng 选项中使用推送是否有任何限制?或者我想在这里改变什么?

您正在推动另一个数组中的数组。您应删除"[]"。

$scope.arealistArray.push({
  id: 'id' + j,
  label: 'aLabel' + j,
  subItem: {
    name: 'aSubItem' + j
  }
});

这是一个基于您的代码的工作小提琴。

$scope.arealistArray.push([{id: 'id'+j,label: 'aLabel'+j,subItem: { 
name: 'aSubItem'+j }}]);

如果像上面一样,您需要指定索引或其他

 ng-options="item as item.label for item in items[0] track by item.id"

如果它是一个对象,则在执行推送时删除 []。

$scope.arealistArray.push({id: 'id'+j,label: 'aLabel'+j,subItem: { 
name: 'aSubItem'+j }});

var app = angular.module('myapp', []);
app.controller('mycontroller', function($scope) {
$scope.arealistArray=[];
$scope.items=[]; 
for(j=1;j<3;j++){
    $scope.arealistArray.push({id: 'id'+j,label: 'aLabel'+j,subItem: { 
    name: 'aSubItem'+j }});
} 
$scope.items = $scope.arealistArray;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="mycontroller" class="col-md-8">
    <select  ng-options="item as item.label for item in items track by 
item.id" ng-model="selected">
        <option></option>
    </select>
</div>

最新更新