ng-repeat 在将信息发送回控制器时会出现问题,因为通常我们向用户显示名称,但使用选项的 ID/Index 进行后端操作。
简单的话- 使用ng-options您可以使用完整的JavaScript 对象。
<!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="selectedName" ng-options="x.name for x in names">
</select>
<!--It will display complete object-->
{{selectedName}}
<!--It will display object's age-->
{{selectedName.age}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = [{"name":"Neeraj","age":"21"}, {"name":"John","age":"22"}, {"name":"David","age":"23"}];
});
</script>
</body>
</html>
但是使用ng-repeat你必须处理string。
<!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="selectedName">
<option ng-repeat="x in names">{{x.name}}</option>
</select>
<!--It will display only selected name not complete object-->
{{selectedName}}
<!--It won't work-->
{{selectedName.age}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = [{"name":"Neeraj","age":"21"},{"name":"John","age":"22"},{"name":"David","age":"23"}];
});
</script>
<p>This example shows how to fill a dropdown list using the ng-repeat directive.</p>
</body>
</html>