我重新问这个问题是因为我之前遗漏了重要信息。
我有一个日期模型,它根据此更改输入的值:AngularJS: How to set default value to ng-model="searchText"? .
<div class="modal-body">
<div style="display:inline-block; margin-bottom:20px;">
<h3 style="float:left;">Set All Dates: </h3>
<span style="padding-top:15px; padding-left:7px;" class="input-group date">
<input id="setAllEffectiveDates" type="text" data-ng-model="date" value="" class="form-control input-sm">
<span class="input-group-addon"><i class="glyphicon glyphicon-th"></i></span>
</span>
</div>
<table class="table table-bordered">
<tbody data-ng-repeat="(associatedContract,ndc) in ndcs">
<tr>
<td>
<div class="input-group date updateIt">
<input id="effectiveDate" type="text" data-ng-model="date" class="form-control input-sm">
<span class="input-group-addon"><i class="glyphicon glyphicon-th"></i></span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
上面的内容按预期工作,当我选择一个日期时,所有输入都会更改为该所选日期。
我的问题是我想向字段添加默认值。该值是一个正在迭代的变量:<tbody data-ng-repeat="(associatedContract,ndc) in ndcs">
.
<input id="effectiveDate" type="text" data-ng-model="date" ng-init="date=ndc.value" class="form-control input-sm">
添加ng-init="date=ndc.value"
确实按预期添加了来自 Controller 的默认值。但它删除了数据绑定(bind)。更改 input id="setAllEffectiveDates"
时,该字段不再更新.
如何才能在使用默认值的同时使数据绑定(bind)正常工作?
编辑:
我添加了 ng-change 的更新功能:
<input id="setAllEffectiveDates" ng-change="updateEffectiveDates(date)" type="text" data-ng-model="date" value="" class="form-control input-sm">
然后做了一个函数:
$scope.updateEffectiveDates = function (date) {
angular.forEach($scope.ndcs, function (ndc) {
ndc.value = date;
});
console.log($scope.ndcs);
};
这看起来更新了模型,但没有更新页面上的字段。
最佳答案
我怀疑 ng-init
正在为 ng-repeat
创建的每个新作用域创建一个新的 date
变量,所以它不会'不再受 Controller 的约束。如果您只需要一个日期,请尝试将其设置为 Controller 中存在的一个对象:
Controller :
$scope.obj = {
date: null
};
查看:
<input ng-init="obj.date=ndc.value">
编辑:只需绑定(bind)到每个数组元素上已有的日期即可:
data-ng-model="ndc.date"ng-change="setOtherDates()"
最终答案:
<input id="setAllEffectiveDates" ng-change="updateEffectiveDates(date)" type="text" data-ng-model="date" value="" class="form-control input-sm">
然后:
<input id="effectiveDate" type="text" data-ng-model="ndc.value" class="form-control input-sm">
具有功能:
$scope.updateEffectiveDates = function (date) {
angular.forEach($scope.ndcs, function (ndc) {
ndc.value = date;
});
console.log($scope.ndcs);
};
关于javascript - 在 ng-repeat 中向字段添加默认值时数据绑定(bind)停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44528013/