[英]AngularJS : Remove empty select option in angular ng-repeat
I am using ng-repeat to render options with different value and text here, and also setting the default one.But again angular adds an empty undefined option. 我在这里使用ng-repeat来渲染具有不同值和文本的选项,并且还设置默认值。但是,再次使用angular添加一个空的未定义选项。
<select ng-model="newItem.financial_year_id" required style="min-width:180px;">
<option ng-repeat="financial in account_year" value="{{financial.id}}" ng-selected="financial.status=='Active'">{{financial.financial_year}}</option>
</select>
Now the active one is selected but the empty option still rendering. 现在选择了活动的一个,但空选项仍然呈现。
The empty option is generated when a value referenced by ng-model doesn't exist in a set of options passed to ng-options. 当传递给ng-options的一组选项中不存在ng-model引用的值时,将生成空选项。
You can find the full answer+example on stackoverflow. 您可以在stackoverflow上找到完整的答案+示例。 here's the link
这是链接
UPDATE: 更新:
here's an example: 这是一个例子:
<select ng-model="newItem.financial_year_id" required style="min-width:180px;">
<option ng-repeat="financial in account_year" value="{{financial.id}}" ng-selected="financial.status=='Active'">{{financial.financial_year}}</option>
</select>
in controller: 在控制器中:
$scope.newItem={};
$scope.account_year=[{id:1,financial_year:"2013-2014",status:"Active"},
{id:2,financial_year:"2014-2015",status:"Inactive"}]
//remove empty option
$scope.newItem.financial_year_id=$scope.account_year[0].id;
live example: http://jsfiddle.net/choroshin/5YDJW/7/ 实例: http : //jsfiddle.net/choroshin/5YDJW/7/
Try ng-options
instead: 请尝试使用
ng-options
:
<select ng-model="selectedFinancial" ng-options="c.financial_year for c in account_year"
required style="min-width:180px;">
</select>
You should think about redesigning your model like that to use ng-options
. 你应该考虑重新设计你的模型,使用
ng-options
。 When we use <select>
, there is only 1 selected item and this item should be a property of $scope
referencing an item in the list => we don't need to duplicate 1 more property with "active"
and "inactive"
for all objects. 当我们使用
<select>
,只有1个选定的项目,这个项目应该是引用列表中项目的$scope
的属性=>我们不需要复制另外1个具有"active"
和"inactive"
属性所有物体。
Your current model design makes sense when there are more than 1 selected item, but if there are more than 1, we should use a list of checkboxes instead of <select>
当有超过1个选定项目时,您当前的模型设计是有意义的,但如果有超过1个,我们应该使用复选框列表而不是
<select>
If you want to bind with Id, try this: 如果要与Id绑定,请尝试以下操作:
<select ng-model="selectedFinancialId" ng-options="c.id as c.financial_year for c in account_year"
required style="min-width:180px;">
</select>
Ng-option is also a good way. Ng-option也是一个好方法。 But if you really want ng-repeat then use like this.
但如果你真的想要ng-repeat那么就这样使用。
$scope.newItem.financial_year_id=" ";
Initialize the variable when you start the controller. 启动控制器时初始化变量。 If you not initialize it then it takes as undefined.
如果你没有初始化它,那么它需要未定义。 So the first empty value is present.
所以第一个空值存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.