Как заполнить поле ввода на основе поля выбора и наоборот - PullRequest
0 голосов
/ 05 июля 2018

Я пытаюсь заполнить поле выбора и поле ввода.

Значение,

  1. Всякий раз, когда кто-то пытается выбрать страну, я устанавливаю соответствующую валюту в поле ввода и отображаю страну + валюту в выводе.
  2. Всякий раз, когда кто-то пытается ввести валюту, я устанавливаю страну в поле параметров и показываю страну + валюту в выводе.

Мой контроллер:

app.controller('MainCtrl', function ($scope) {           
    $scope.$watch('countrySelect', function () {
        for ($i = 0; $i < arr.length; $i++) {
            var temp = arr[$i]['select'];
            if (temp === $scope.countrySelect) {
                $scope.outputCountry = arr[$i].country + arr[$i].currency;
                $scope.countryCurrency = arr[$i].currency;
            }
        }
    });

    $scope.$watch('countryCurrency', function () {
        for ($i = 0; $i < arr.length; $i++) {
            var temp = arr[$i]['currency'];
            if (temp === $scope.countryCurrency) {
                $scope.outputCountry = arr[$i].country + $scope.countryCurrency;
                $scope.countrySelect = arr[$i].country;
            }
        }
    });
});

Соответствующий div:

<div ng-controller="MainCtrl">
    <form action="#">
        <select ng-model="countrySelect" ng-init="countrySelect = 11">
            <option value="11">US</option>
            <option value="12">UK</option>
        </select>
        <input ng-model="countryCurrency" />
        <input ng-model="outputCountry" />
    </form>
</div>

Я придумал этот Плункер .

  1. Есть ли лучший способ добиться того же самого без использования $scope.watch и многократного обстрела?
  2. Во время загрузки (перед выбором любой страны по умолчанию) $scope.watch не срабатывает и значения не заполняются вообще.

Здесь есть указатели?

Ответы [ 2 ]

0 голосов
/ 05 июля 2018

Напишите «usd» или «sek» в первом поле ввода или выберите страну в поле выбора.

angular.module("app", [])
.controller('MainCtrl', function ($scope)
{
    $scope.countryCurrency = "";
    $scope.outputCountry = "";
    $scope.countries = [
        {
            name: "Sweden",
            currency: "SEK"
        },
        {
            name: "United States",
            currency: "USD"
        }
    ];
    $scope.selected = {
        country: $scope.countries[0].name
    };

    $scope.$watch("selected.country", function()
    {
        var country = $scope.countries.find(function(country)
        {
            return country.name == $scope.selected.country;
        });

        if(country)
        {
            $scope.outputCountry = country.name + country.currency;
            $scope.countryCurrency = country.currency;
        }
        else
        {
            $scope.outputCountry = "";
            $scope.countryCurrency = "";
        }
    });

    $scope.$watch("countryCurrency", function()
    {
        var country = $scope.countries.find(function(country)
        {
            return country.currency == $scope.countryCurrency.toUpperCase().trim();
        });

        if(country)
        {
            $scope.outputCountry = country.name + $scope.countryCurrency;
            $scope.selected.country = country.name;
        }
        else
        {
            $scope.outputCountry = "";
        }
    });
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body>
<div ng-controller="MainCtrl">
    <form action="#">
        <select ng-model="selected.country">
            <option ng-repeat="country in countries" ng-value="country.name">{{ country.name }}</option>
        </select>
        <input ng-model="countryCurrency" />
        <input ng-model="outputCountry" />
    </form>
</div>
</body>
</html>
0 голосов
/ 05 июля 2018

<form>
Select your favorite fruit:
<select id="mySelect" onclick="myFunction()" >
  <option value="apple">Apple</option>
  <option value="orange">Orange</option>
  <option value="pineapple">Pineapple</option>
  <option value="banana">Banana</option>
</select>

<input type = "text" id = "TextBox1">


</form>




<script>
function myFunction() {
    var x = document.getElementById("mySelect").value;
    document.getElementById("TextBox1").value = x;
    
}
</script>

</body>
</html>

Это то, что вы ищете ??

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...