gpt4 book ai didi

angularjs - 使用 AngularJS 从选择选项中删除空白选项

转载 作者:行者123 更新时间:2023-12-02 19:29:10 26 4
gpt4 key购买 nike

我是 AngularJS 新手。我查了很多资料,还是没有解决我的问题。

我第一次在选择框中得到一个空白选项。

这是我的 HTML 代码

<div ng-app="MyApp1">
<div ng-controller="MyController">
<input type="text" ng-model="feed.name" placeholder="Name" />
<select ng-model="feed.config">
<option ng-repeat="template in configs">{{template.name}}</option>
</select>
</div>
</div>

JS

var MyApp=angular.module('MyApp1',[])
MyApp.controller('MyController', function($scope) {
$scope.feed = {};

//Configuration
$scope.configs = [
{'name': 'Config 1',
'value': 'config1'},
{'name': 'Config 2',
'value': 'config2'},
{'name': 'Config 3',
'value': 'config3'}
];
//Setting first option as selected in configuration select
$scope.feed.config = $scope.configs[0].value;
});

但是好像不行。我怎样才能解决这个问题?这是JSFiddle Demo

最佳答案

供引用:Why does angularjs include an empty option in select

The empty option is generated when a value referenced by ng-model doesn't exist in a set of options passed to ng-options. This happens to prevent accidental model selection: AngularJS can see that the initial model is either undefined or not in the set of options and don't want to decide model value on its own.

In short: the empty option means that no valid model is selected (by valid I mean: from the set of options). You need to select a valid model value to get rid of this empty option.

像这样更改你的代码

var MyApp=angular.module('MyApp1',[])
MyApp.controller('MyController', function($scope) {
$scope.feed = {};

//Configuration
$scope.feed.configs = [
{'name': 'Config 1',
'value': 'config1'},
{'name': 'Config 2',
'value': 'config2'},
{'name': 'Config 3',
'value': 'config3'}
];
//Setting first option as selected in configuration select
$scope.feed.config = $scope.feed.configs[0].value;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="MyApp1">
<div ng-controller="MyController">
<input type="text" ng-model="feed.name" placeholder="Name" />
<!-- <select ng-model="feed.config">
<option ng-repeat="template in configs">{{template.name}}</option>
</select> -->
<select ng-model="feed.config" ng-options="template.value as template.name for template in feed.configs">
</select>
</div>
</div>

Working JSFiddle Demo

更新(2015 年 12 月 31 日)

如果您不想设置默认值并希望删除空白选项,

<select ng-model="feed.config" ng-options="template.value as template.name for template in feed.configs">
<option value="" selected="selected">Choose</option>
</select>

并且在JS中不需要初始化值。

$scope.feed.config = $scope.feed.configs[0].value;

关于angularjs - 使用 AngularJS 从选择选项中删除空白选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20738953/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com