ng-options 从字典中传递值

ng-options pass value from dictionary

我有字典,所以在 json

Object {1: "value1", 4: "value2" }

我想传递选定的值而不是键。

现在我这样编码:

<select ng-model="myModel.myValue" ng-options="key as item for (key, value) in items" class="form-control">
<option value="">Choose</option>                                          </select>

尝试在选项中使用 ng-repeat 而不是 ng-options

var app = angular.module('anApp', []);
app.controller('aCtrl', function($scope) { 
  $scope.items = {1: "value1", 4: "value2" };
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="anApp" ng-controller="aCtrl">
  <select ng-model="myModel.myValue" class="form-control">
     <option ng-repeat="(key,value) in items" value="{{value}}">
       {{value}}
     </option>                                        
  </select>
</div>

试试这个

ng-options="value as value for (key, value) in items

ng-options="key as item for (key, value) in items" 在这里你使用键作为值,这是你的答案不起作用的主要原因

您需要使用密钥对的值作为列表的值,并在视图面板中使用相同的值。

angular.module("app",[])
.controller("ctrl",function($scope){
 $scope.items = {1: "value1", 4: "value2" };
  $scope.myModel = {}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<select ng-model="myModel.myValue" ng-options="value as value for (key, value) in items"   ">                                     </select>
{{myModel.myValue}}
</div>

使用这个 ng-options="value as value for (key, value) in items"。它将为 ng-model

分配值而不是键

angular.module("app",[])
.controller("ctrl",function($scope){
 $scope.items = {1: "value1", 4: "value2" };
  $scope.myModel = {}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<select ng-model="myModel.myValue" ng-options="value as value for (key, value) in items" class="form-control">
<option value="">Choose</option>                                          </select>
{{myModel.myValue}}
</div>

看到这个:

angular.module("app",[])
.controller("ctrl",function($scope){
 $scope.items = {1: "value1", 4: "value2" };
  $scope.myModel = "value1";
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<select ng-model="myModel" ng-options="value for (key, value) in items"   ">                                     </select>
{{myModel.myValue}}
</div>