2016-04-11 20 views
0

私は2つのモデルを各入力フィールドに1つずつ持っています。私はデータを出力するコントローラを持っています。そのコントローラーの中で、私はこれら2つの入力モデルをマージする新しい変数を定義しました。しかし、その変数はモデルの変更によって変化しません。モデルの1つが変更された場合、その変数を更新するにはどうすればよいですか?モデルが変更されたときの変数の変更

これは私のグローバルコントローラの一部です:

$http.get('/dates').then(function(response){ 
    $scope.years = response.data.years 
    $scope.months = [] 
    for (var i = 0; i < 12; i++) { 
    $scope.months.push(response.data.months[i]) 
    } 
}); 

これは私が見たいモデルとビューです:

<div class="input-dual"> 
    <div class="input-dual-inner"> 
     <span>Datum polaska:</span> 
     <select ng-model="selectedYear" ng-options="year as year for year in years"> 
     </select> 
    </div> 
    <div class="input-dual-inner"> 
     <span style="opacity: 0; cursor: default">.</span> 
     <select ng-model='selectedMonth' ng-options='month as month.name for month in months'> 
     </select> 
    </div> 
    </div> 

そして、これは変更を監視して、新しいモデルを割り当てる必要がありますコントローラであります:

AppControllers.controller('DataOutput', [ 
    '$scope','$http', 
    function($scope, $http){ 
    $scope.selectedDate = $scope.selectedYear + "-" + $scope.selectedMonth 
    } 
]); 
+0

ため、このplnkrリンクこのコードを追加します。スコープの問題を単純化するのに役立ちます。 – isherwood

+0

あなたのコード '$ scope.selectedDate = $ scope.selectedYear +" - "+ $ scope.selectedMonth'はコントローラ初期化時にのみ実行されます。これは実際にバインディングを作成するものではなく、1回限りのコードです。 '$ watch'や' ng-change'ハンドラを使う必要があります。 – ryanyuyu

+0

@ryanyuyuええ、私はそれを知っている、それは私が提案を求める理由です – Kunok

答えて

2

あなたはwatch

var createDate = function(newValue, oldValue) { $scope.selectedDate = $scope.selectedYear + "-" + $scope.selectedMonth }; $scope.$watch("selectedYear", createDate); $scope.$watch("selectedMonth", createDate); 

モデルの両方に第二のアプローチを追加することができます

使用ng-changeあなたselect要素

<div class="input-dual"> 
    <div class="input-dual-inner"> 
     <span>Datum polaska:</span> 
     <select ng-model="selectedYear" ng-change="createDate()" ng-options="year as year for year in years"> 
     </select> 
    </div> 
    <div class="input-dual-inner"> 
     <span style="opacity: 0; cursor: default">.</span> 
     <select ng-model='selectedMonth' ng-change="createDate()" ng-options='month as month.name for month in months'> 
     </select> 
    </div> 
</div> 

とコントローラでのあなたはcontrollerAs構文に見えるかもしれません

$scope.createDate = function() { 
    $scope.selectedDate = $scope.selectedYear + "-" + $scope.selectedMonth 
}; 

チェック参照https://plnkr.co/edit/8179tojufhGMj5SbUujJ?p=preview

3

$ watchを使用してみてください。このような何か:あなたは

この

最初のアプローチを達成するための2つの方法があり

AppControllers.controller('DataOutput', [ 
    '$scope','$http', 
    function($scope, $http){ 
    $scope.$watch('selectedYear', updateSelectedDate); 
    $scope.$watch('selectedMonth', updateSelectedDate); 
    function updateSelectedDate() { 
     $scope.selectedDate = $scope.selectedYear + "-" + $scope.selectedMonth; 
    } 
}]); 
関連する問題