2017-06-13 69 views
0

我在重複提問,因爲我之前忽略了重要信息。向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); 
    }; 

這看起來像它更新模型,但不字段在頁面上。

+0

NG-INIT用於調用您希望在該項目被實例化執行的功能。一般建議絕對不要用於任何事情。你能在你的控制器中初始化模型到所需的值嗎? –

+0

@MikeFeltman是的,但有多個日期值,這就是爲什麼有ng重複。你是在說一個數組還是其他的東西? –

+0

模型中只有一個日期。您的意思是使用associatedContract或ndc對象上提供的日期屬性嗎? –

回答

1

我懷疑ng-init正在對由ng-repeat每個新創建的作用域的新date變量,因此它不會從您的控制器了綁定。如果你只需要一個日期,嘗試將其設置爲存在於你的控制器對象:

控制器:

$scope.obj = { 
    date: null 
}; 

查看:

<input ng-init="obj.date=ndc.value"> 

編輯:只需綁定的日期你已經在每個陣列元素上有:

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); 
    }; 
+0

這會重新啓用數據綁定,但它也會將所有默認傳入值設置爲1個特定值。 ng-repeat有多個進來。 –

+0

也許你需要做:'data-ng-model =「ndc.date」ng-init =「ndc.date = ndc.value」' –

+0

好吧,如果我使用上述。如何在ng-update之後更改所有ndc.date值?我是否也將選擇器字段模型設置爲ndc.date?即使它在ng-repeat之外? '' –

相關問題