我有这个HTML标记:
<div ng-repeat="prop in props" style="margin-bottom: 10px;">
<label class="col-md-4 control-label">Property {{$index + 1}} ({{prop.AddressLine1}})</label><div class="col-md-8">
<select ng-model="prop.Grade" class="form-control" ng-options="opt.name for opt in propGradings track by opt.id"> <option ng-selected="{{option.id == prop.Grade}}" ng-repeat="option in propGradings" ng-value="{{option.id}}">{{option.name}}</option> </select>
</div>
</div>
这个静态数组填写下拉列表:
$scope.propGradings = [{ name: "1", id: 1 }, { name: "2", id: 2 }, { name: "3", id: 3 }, { name: "4", id: 4 }];
我可以在下拉列表中加载项目,但我无法根据prop.Grade值预先选择正确的值。
HTML输出:
知道我做错了什么吗?
答案 0 :(得分:0)
从下拉列表中选择选项时,键入以进行绑定。使用ng-options时,您可以使用作为将某些内容绑定到模型作为非字符串值。在您的情况下,您可能希望绑定到id的整数值。
语法 select
label
value
array
&GT; select:绑定到ng-model的值 &GT; label:下拉列表中明显显示的价值 &GT; value:数组中的当前项目 &GT; array:用于生成选项的数据源
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
$scope.props = [{Grade: 1}];
$scope.propGradings = [{ name: "1", id: 1 }, { name: "2", id: 2 }, { name: "3", id: 3 }, { name: "4", id: 4 }];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
Binding with an integer value:
<div ng-repeat="prop in props" style="margin-bottom: 10px;">
<label class="col-md-4 control-label">Property {{$index + 1}} ({{prop.AddressLine1}})</label>
<div class="col-md-8">
<select ng-model="prop.Grade" class="form-control" ng-options="opt.id as opt.name for opt in propGradings">
<option ng-selected="{{option.id == prop.Grade}}" ng-repeat="option in propGradings" ng-value="{{option.id}}">{{option.name}}</option>
</select>
</div>
</div>
</div>
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
$scope.props = [{Grade: "1"}];
$scope.propGradings = [{ name: "1", id: 1 }, { name: "2", id: 2 }, { name: "3", id: 3 }, { name: "4", id: 4 }];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
Binding with a string value:
<div ng-repeat="prop in props" style="margin-bottom: 10px;">
<label class="col-md-4 control-label">Property {{$index + 1}} ({{prop.AddressLine1}})</label>
<div class="col-md-8">
<select ng-model="prop.Grade" class="form-control" ng-options="opt.name as opt.name for opt in propGradings">
<option ng-selected="{{option.id == prop.Grade}}" ng-repeat="option in propGradings" ng-value="{{option.id}}">{{option.name}}</option>
</select>
</div>
</div>
</div>