我有一个通过web api填充的下拉列表(选择)。 web api的返回具有以下结构:
{
"Id": 1,
"Description": "A description"
}
我需要的是,当我选择一个选项时,我想要相应的标签(或文本)和值。这就是我所拥有的:
<select class="form-control" ng-model="requestTypeList"
ng-change="selectChange"
ng-options="requestType.Id as requestType.Description for requestType
in requestTypes">
</select>
<input type="text" ng-model="RequestTypeID" /><br/>
<input type="text" ng-model="RequestTypeDescription" />
我的控制器看起来像这样:
(function (app) {
var requestCtrl = function ($scope, $http, requestTypeService) {
$scope.requestRows = [];
$scope.selectChange = function() {
$scope.RequestTypeID = $scope.requestTypeList.value;
$scope.RequestTypeDescription = $scope.requestTypeList.label;
}
requestTypeService.getAll().success(function (data) {
$scope.requestTypes = data;
});
$scope.addRequest = function () {
var requestRow = {
RequestTypeID: $scope.RequestTypeID, // Here I need the selected value
RequestTypeDescription: $scope.RequestTypeDescription, // Here I need the selected Description
EventColor: $scope.EventColor
};
$scope.requestRows.push(requestRow);
};
$scope.removePlanboardRequest = function (index) {
$scope.planboardRequests.splice(index, 1);
};
};
app.controller("PlanboardRequestCtrl", planboardRequestCtrl);
}(angular.module("planboardApp")));
答案 0 :(得分:1)
设置ng-options
以选择整个对象而不仅仅是它的ID。
同时修复()
ng-change
修复label
value
和selectChange ()
属性
<select class="form-control" ng-model="requestTypeList"
ng-change="selectChange()"
ng-options="requestType as requestType.Description for requestType
in requestTypes">
</select>
JS
$scope.selectChange = function() {
$scope.RequestTypeID = $scope.requestTypeList.Id;
$scope.RequestTypeDescription = $scope.requestTypeList.Description;
}
通过设置ng-options来选择整个对象,您实际上不需要使用RequestTypeID
和RequestTypeDescription
等单个变量,因为您需要查看视图或$http
已经在requestTypeList
答案 1 :(得分:0)
首先,您需要设置ng-model
ng-options
来接收object
而不是id
。
另外在你的事业中我认为没有必要使用ng-change
指令,你可以简单地将ng-model属性设置为输入,如下所示:
(function() {
"use strict";
angular.module('app', [])
.controller('mainCtrl', function($scope) {
$scope.requestTypes = [
{
"Id":1,
"Description":"First description"
},
{
"Id":2,
"Description":"Second description"
},
{
"Id":3,
"Description":"Third description"
}
];
});
})();
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl">
Requesters: <select class="form-control" ng-model="requestTypeList" ng-options="requestType as requestType.Description for requestType in requestTypes">
</select>
<hr>
<label for="requestId">Id: </label>
<input type="text" id="requestId" ng-model="requestTypeList.Id">
<br>
<label for="requestDesc">Description: </label>
<input type="text" id="requestDesc" ng-model="requestTypeList.Description">
</body>
</html>