为什么ng-model重置选择的选项?

时间:2015-03-22 15:48:40

标签: javascript angularjs

选择列表由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>

如何解决?

2 个答案:

答案 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