<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myctrl', function($scope) {
$scope.state = [{name:'TamilNadu', code:1}, {name:'Kerala', code:2}, {name:'Karnataka', code:3}];
$scope.onChange = function() {
var a = this.drop.state; }
});
</script>
<body>
<div ng-app="myApp" ng-controller="myctrl">
State :
<select id="stat" ng-model="drop.state" ng-change="onChange()">
<option ng-repeat = "x in state"> {{x.name}} </option>
<select>
</div>
</body>
在此代码中,我可以从变量a中的文本框中获取所选值。现在,我需要获取所选名称的代码值。是否可以使用indexof()。而且我需要动态,即,当选择'状态'时,我需要来自数组的相应“代码”。
答案 0 :(得分:1)
<option value="{{x}}" ng-repeat = "x in state"> {{x.name}} </option>
如果您在Option上添加值,您可能会获得完整的对象,并访问代码和值
答案 1 :(得分:0)
您可以将code
指定为option
<option ng-repeat = "x in state" ng-value="x.code"> {{x.name}}
演示
var app = angular.module('myApp', []);
app.controller('myctrl', function($scope) {
$scope.drop = {}
$scope.state = [{name:'TamilNadu', code:1}, {name:'Kerala', code:2}, {name:'Karnataka', code:3}];
$scope.onChange = function() {
var a = $scope.drop.state
console.log(a)
}
});
&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myctrl">
State :
<select id="stat" ng-model="drop.state" ng-change="onChange()">
<option ng-repeat = "x in state" ng-value="x.code"> {{x.name}} </option>
</select>
</div>
&#13;
答案 2 :(得分:0)
即使其他答案有效,这也是正确的方法:
<select id="stat" ng-model="drop.state" ng-options="x.code as x.name for x in state" ng-change="onChange()">
<option value="">Select a value</option>
</select>
如果ng-change的目的是获取状态代码,这种方式就不需要了。您的ng模型将等于所选的州代码。
答案 3 :(得分:0)
您可以将数据绑定到单个属性。并且可以访问这两个属性。首选ng-options
。
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myctrl', function($scope) {
$scope.state = [{
name: 'TamilNadu',
code: 1
}, {
name: 'Kerala',
code: 2
}, {
name: 'Karnataka',
code: 3
}];
$scope.onChange = function() {
alert(this.drop.state.name);
alert(this.drop.state.code);
}
});
</script>
<body>
<div ng-app="myApp" ng-controller="myctrl">
State :
<select id="stat" ng-model="drop.state" ng-options= "x as x.name for x in state" ng-change="onChange()"> </select>
</div>
</body>
&#13;