Bagaimana cara mendapatkan dua kotak pilih untuk bekerja secara terbalik di angularjs? Saya punya contoh ini.

<select id="srcCurrency" ng-model="params.srcCurrency">                     
    <option>USD</option>
    <option>KRW</option>
</select>
<select id="dstCurrency" ng-model="params.dstCurrency">
   <option >USD/option>
   <option >KRW</option>
</select>

Saya ingin memilih yang berlawanan satu sama lain. Saya punya contoh ini tetapi saya ingin cara yang lebih efisien.

$scope.$watch('params.srcCurrency', function (newValue, oldValue) {
  if ($scope.params.srcCurrency == "USD") {
    $scope.params.dstCurrency = "KRW";
  } else {
    $scope.params.dstCurrency = "USD";
  }

}, true);

$scope.$watch('params.dstCurrency', function (newValue, oldValue) {
  if ($scope.params.dstCurrency == "USD") {
    $scope.params.srcCurrency = "KRW";
  } else {
    $scope.params.srcCurrency = "USD";
  }
}, true);
0
ansatgol 15 Maret 2017, 14:08

2 jawaban

Jawaban Terbaik
<select id="srcCurrency" ng-model="params.srcCurrency" ng-change="switchCurrencies(params.srcCurrency, 'source')">                     
    <option>USD</option>
    <option>KRW</option>
</select>
<select id="dstCurrency" ng-model="params.dstCurrency" ng-change="switchCurrencies(params.dstCurrency, 'dest')">
   <option >USD/option>
   <option >KRW</option>
</select>

Di pengontrol Anda

$scope.switchCurrencies = function(resource, type){
  if(type == 'source'){
    $scope.params.dstCurrency = angular.copy(resource);
  }else{
    $scope.params.srcCurrency = angular.copy(resource);
  }
}
0
Salih Şenol Çakarcı 15 Maret 2017, 12:49

Anda sebaiknya menghindari penggunaan $watch. Alih-alih menggunakan ng-change

0
Murthy M 15 Maret 2017, 11:31