在 angularjs 中显示名称而不是 ID 模式下拉列表
Display name instead ID modal dropdown in angularjs
当我 select 我必须传递国家 ID 时,有一个国家和州的下拉列表,但在点击事件后它应该传递 ID 但显示为名称 我怎样才能做到这一点请指导
<md-select name="state" id="state" placeholder="Select a state" md-no-asterisk="true"
ng-change="getCounties(state)" ng-model="state">
<md-option ng-repeat="item in state track by id"
value="{{item.id}}">
{{item.name}}
</md-option>
</md-select>
{{AddressState}} /* This should be name instead of value how can i display this ? */
<div class="clearfix" ng-click="edit()">
Edit</a></div>
controller.ts :
$scope.AddressState = state;
不要使用 state
作为您的 ng-model
,因为 state
已经是您的数据源。考虑改为使用一个对象来捕获所有用户输入,其中 state
作为 属性。您的 ng-model 将捕获用户选择的 ID,这就是您想要的,您可以使用它来获取州名。
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.userInput = {
state: {}
};
$scope.state = [{
"name": "Califoria",
"id": 1
}, {
"name": "Texas",
"id": 2
}]
$scope.getCounties = function() {
// $scope.userInput.state is updated autmatically with the ID
console.log($scope.userInput)
// the associated data can be found using
let state = $scope.state.find(s => s.id == $scope.userInput.state)
$scope.selectedState = state.name; // for display
}
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="userInput.state" ng-change="getCounties()">
<option ng-repeat="item in state" value="{{item.id}}">
{{item.name}}
</option>
</select>
<p> {{selectedState}} </p>
</div>
当我 select 我必须传递国家 ID 时,有一个国家和州的下拉列表,但在点击事件后它应该传递 ID 但显示为名称 我怎样才能做到这一点请指导
<md-select name="state" id="state" placeholder="Select a state" md-no-asterisk="true"
ng-change="getCounties(state)" ng-model="state">
<md-option ng-repeat="item in state track by id"
value="{{item.id}}">
{{item.name}}
</md-option>
</md-select>
{{AddressState}} /* This should be name instead of value how can i display this ? */
<div class="clearfix" ng-click="edit()">
Edit</a></div>
controller.ts :
$scope.AddressState = state;
不要使用 state
作为您的 ng-model
,因为 state
已经是您的数据源。考虑改为使用一个对象来捕获所有用户输入,其中 state
作为 属性。您的 ng-model 将捕获用户选择的 ID,这就是您想要的,您可以使用它来获取州名。
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.userInput = {
state: {}
};
$scope.state = [{
"name": "Califoria",
"id": 1
}, {
"name": "Texas",
"id": 2
}]
$scope.getCounties = function() {
// $scope.userInput.state is updated autmatically with the ID
console.log($scope.userInput)
// the associated data can be found using
let state = $scope.state.find(s => s.id == $scope.userInput.state)
$scope.selectedState = state.name; // for display
}
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="userInput.state" ng-change="getCounties()">
<option ng-repeat="item in state" value="{{item.id}}">
{{item.name}}
</option>
</select>
<p> {{selectedState}} </p>
</div>