2014-07-02 56 views
1

我有currentDistrict要顯示在頁面上。 初始化爲空字符串:

$scope.currentDistrict = ''; 

,後來被填充了的WebAPI電話:

... 
    $scope.currentDistrict = data.currentDistrict; 
... 

檢索到的區信息顯示在diretive:

<district-selector current="currentDistrict"></district-selector> 

而且,是使用json對象的頁面中的表單:

$scope.address = { 
    'district': $scope.currentDistrict, 
    'name': '', 
    'street': '', 
    'city': '', 
    'state': '', 
    'zip': '', 
    'comments': '' 
}; 

的形式使用該address對象:

我希望在$scope.address.district值會隨currentDistrict改變。說,如果我改變當前的區域,不僅<district-selector>會改變,但表格中的只讀文本框也應該改變。

但它從來沒有。

所以問題是:如何改變$scope.address.district$scope.currentDistrict有變化?

如果'district': $scope.currentDistrict,不會設置綁定,那麼聽取一個變量的更改並應用於另一個變量的正確方法是什麼?

回答

1

這種情況是完美的$watch功能:

$scope.$watch('currentDistrict', function(newVal, oldVal) { 
    $scope.address.district = newVal; 
}); 

通過該控制器具有這裏面的手錶,每當currentDistrict的值發生變化,它將在address.district反映。

+0

謝謝。第一次聽說'$ watch'。它只是工作! – Blaise

0

您可以使用updateOn從ngModelsOptions

使用ngModelOptions您可以指定事件的自定義列表,將 觸發來自AngularJS文檔模型更新....

簡單示例

<input type="text" name="userName" 
      ng-model="user.name" 
      ng-model-options="{ updateOn: 'blur' }" 
      ng-keyup="cancel($event)" /><br /> 

在你的情況,當updat E /變化currentDistrict然後更改address.district

相關問題