选择列表由php在页面中生成。当我将ng-model
添加到此选择时,它会重置所选的默认选项。
<select name="day" ng-model="day" class="form-control" ng-required="true" required="required">
<option value="22" selected="selected">22</option>
<option value="23">23</option>
</select>
如何解决?
答案 0 :(得分:1)
假设var currentDay = '' + (new Date()).getDate();
您应该使用ng-options
并设置$scope.day = currentDay;
来选择当天。
刚刚讨论过ng-options
与重复选项 here
一般来说,ng-options
比<option ng-repeat='...'>
更好(没有双关语),因为它更灵活。
如果您不想使用ng-options
,请将$scope.day = currentDay;
放入您的范围并删除selected="selected"
,因为绑定将在$scope.day
和<select name="day" ng-model="day" class="form-control" ng-required="true" required="required">
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
</select>
之间完成选项。 请参阅fiddle
<强> 模板: 强>
$scope.day = currentDay; // Get the current day of month as a string.
<强> 控制器: 强>
{{1}}
答案 1 :(得分:1)
有一个简单的解决方案,
如果您从后端创建select
,请将ng-init
设置如下,
<select name="day" ng-model="day" ng-init="day=22"...
ng-init="day=22"
将day
模型初始化为所选值(22)
。
这里是the punker
或
使用angularjs控制器函数初始化范围变量及其最佳实践。
对于ex:,
<body ng-controller="MainCtrl" ng-init="initializeScopeVariables(22)">
在控制器中,
$scope.initializeScopeVariables = function(initSelectedVal) {
$scope.day = initSelectedVal;
};
这里是the Plunker