Kunok
Kunok

Reputation: 8759

Change variable when a model is changed

I have two models, one for each input field. I have a controller that outputs data. Inside that controller I defined new variable that merges these two input models. However that variable doesn't change upon model changes. How do I update that variable when one of models change?

This is part of my global controller:

$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])
  }
});

This is view with model that I want to watch:

  <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>

And this is controller that should watch for changes and assign new model:

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

Upvotes: 0

Views: 1168

Answers (2)

tpsilva
tpsilva

Reputation: 1463

Try using $watch. Something like this:

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

Upvotes: 3

S4beR
S4beR

Reputation: 1847

You have two ways to achieve this

First Approach

You can add a watch on both of your model

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

$scope.$watch("selectedYear", createDate);
$scope.$watch("selectedMonth", createDate);

Second Approach

Use ng-change on you select element

<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>

and in controller add this code

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

check this plnkr link for reference https://plnkr.co/edit/8179tojufhGMj5SbUujJ?p=preview

Upvotes: 4

Related Questions