[英]Default option in select
I have this very simple select element: 我有这个非常简单的选择元素:
<label>Items per page</label>
<select class="form-control input-sm w25" ng-model="itemsPerPage">
<option value="5">5</option>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
</select>
with controller: 与控制器:
$scope.itemsPerPage = 5; // default value
But the default value is a blank option and the default value attempt doesn't do anything. 但默认值为空白选项,默认值尝试不执行任何操作。
How do I make the value 5 the default? 如何将值5设为默认值?
Angular可能将该值转换为字符串,所以:
$scope.itemsPerPage = "5";
The blank option appears because ng-model can't find an option that matches the value of the bound property (option values are converted to string and the bound property is number). 出现空白选项是因为ng-model无法找到与绑定属性值匹配的选项(选项值转换为字符串,绑定属性为数字)。
If you don't want to change the type of your itemsPerPage
property and make it a string, you can keep a number and define, in your $scope
, an object with a getter and setter that will take care of the type conversion. 如果您不想更改
itemsPerPage
属性的类型并使其成为字符串,则可以保留一个数字,并在$scope
定义一个带有getter和setter的对象,该对象将负责类型转换。
angular.module('dummyApp', []) .controller('DummyController', function($scope) { var itemsPerPage = 5; // still a number Object.defineProperty($scope, "itemsPerPage", { get: function() { return itemsPerPage + ""; }, set: function(newValue) { itemsPerPage = parseInt(newValue); } }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.js"></script> <div ng-app="dummyApp" ng-controller="DummyController"> <label>Items per page</label> <select class="form-control input-sm w25" ng-model="itemsPerPage"> <option value="5">5</option> <option value="10">10</option> <option value="25">25</option> <option value="50">50</option> </select> </div>
<option value="5" selected>5</option>
这应该工作^^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.