AngularJS:删除角度ng-repeat中的空选择选项

dev*_*evo 13 javascript angularjs angularjs-directive angularjs-scope angularjs-ng-repeat

我在这里使用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>
Run Code Online (Sandbox Code Playgroud)

现在选择了活动的一个,但空选项仍然呈现.

Ale*_*hin 19

当传递给ng-options的一组选项中不存在ng-model引用的值时,将生成空选项.

您可以在stackoverflow上找到完整的答案+示例.这是链接

更新:

这是一个例子:

 <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>
Run Code Online (Sandbox Code Playgroud)

在控制器中:

$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;
Run Code Online (Sandbox Code Playgroud)

实例:http: //jsfiddle.net/choroshin/5YDJW/7/


Kha*_* TO 9

尝试ng-options改为:

<select ng-model="selectedFinancial" ng-options="c.financial_year for c in account_year"
        required style="min-width:180px;">
</select>
Run Code Online (Sandbox Code Playgroud)

DEMO

你应该考虑重新设计你想要使用的模型ng-options.当我们使用<select>,只有1所选的项目,这个项目应该是一个属性$scope引用了列表中的项目=>我们并不需要复制1更多的财产与"active""inactive"所有对象.

当有超过1个选定项目时,您当前的模型设计是有意义的,但如果有超过1个,我们应该使用复选框列表而不是 <select>

如果要与Id绑定,请尝试以下操作:

<select ng-model="selectedFinancialId" ng-options="c.id as c.financial_year for c in account_year"
        required style="min-width:180px;">
</select>
Run Code Online (Sandbox Code Playgroud)

DEMO