我在重複提問,因爲我之前忽略了重要信息。向ng-repeat中的字段添加默認值時數據綁定停止
我有一個日期模型,它改變了基於這個輸入的值: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"
確實增加了來自控制器的默認值如預期。但它會刪除數據綁定。更改input id="setAllEffectiveDates"
時,該字段不再更新。
我怎樣纔能有默認值,但也有數據綁定工作?
編輯:
更新功能我加入NG-變化:
<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用於調用您希望在該項目被實例化執行的功能。一般建議絕對不要用於任何事情。你能在你的控制器中初始化模型到所需的值嗎? –
@MikeFeltman是的,但有多個日期值,這就是爲什麼有ng重複。你是在說一個數組還是其他的東西? –
模型中只有一個日期。您的意思是使用associatedContract或ndc對象上提供的日期屬性嗎? –