我有一个显示美国州的菜单供用户选择。在弹出的菜单中,我想显示2个字母的状态代码和状态名称,但是一旦用户选择状态,我只想显示2个字母的代码。
我的菜单是
<select ng-model="ctrl.user.state" name="state"
ng-options="option.code + ' - '+ option.name for option in ctrl.state.options | orderBy: 'name' track by option.code"
class="form-control" required></select>
以格式CT - Connecticut
显示状态,给定我的JSON数据,结构为(部分):
{
"name": "Connecticut",
"code": "CT"
},
答案 0 :(得分:0)
我希望这接近你想要的。我在options数组上再使用了一个属性,并在ng-change上更改了文本。
http://jsfiddle.net/KN9xx/1433/
HTML
<div ng-app="myapp">
<div ng-controller="FirstCtrl">
<select ng-model="selectedValue" name="state"
ng-options="option.code as option.code + option.nameTemplate for option in options" ng-change="changeText(selectedValue)"
class="form-control" required></select>
</div>
</div>
JS
var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function ($scope) {
$scope.options = [
{
"name": "Connecticut",
"nameTemplate": "- Connecticute",
"code": "CT"
},
{
"name": "Connecticut",
"nameTemplate": "- Connecticute",
"code": "AB"
}
];
$scope.selectedValue = "";
$scope.changeText = function(selectedValue) {
for(var i = 0, m = $scope.options.length; i < m; i++) {
if($scope.options[i].code === selectedValue) {
$scope.options[i].nameTemplate = "";
}else {
$scope.options[i].nameTemplate = " - " + $scope.options[i].name;
}
}
}
});
代码肯定有所改进,但想法是更改为ng-options中的文本。如果您有任何疑问,请告诉我们。)