簡體   English   中英

在Angular.js中連接/同步輸入/表單字段

[英]Connecting/synchronizing input/form fields in Angular.js

我有幾個相互關聯的表單字段,我希望所有表單字段都基於使用<select>元素的單個選擇進行更新。

說一個用戶在表單字段選擇一個特定的國家,我再想了countryCode領域和currency領域相對於用戶選擇什么國家得到更新。

例如:

的HTML

<select name="country" ng-options="item.country for item in countries">
   <option value="">Pick a country</option>
</select>

<input name="countryCode" type="text" placeholder="Country Code">
<input name="currency" type="text" placeholder="Currency">

角度的

.controller('exampleCtrl', function {
  $scope.countries = [
    { country: "Sweden" },
    { country: "USA" },
    { country: "Canada" }
  ];

  $scope.currencies = [
    { currency: "SEK" },
    { currency: "USD" },
    { currency: "CAD" }
  ];

  $scope.countryCodes = [
    { countryCode: "SE" },
    { countryCode: "US" },
    { countryCode: "CA" }
  ];

});

我猜最明顯的方法是使用ng-model指令,但是我已經在使用它來收集每個表單元素的信息,以驗證表單並將其發送到服務器。

我將如何使用Angular.js聰明地解決此問題?

非常感謝!

這是我的處理方式-希望對您有所幫助!

標記

<div ng-app>
    <div ng-controller="Ctrl">
        <select name="country" ng-options="item.country for item in countries" ng-model="currentItem" ng-change="updateVals()">
            <option value="">Pick a country</option>
        </select>

        <input name="countryCode" type="text" placeholder="Country Code" ng-model="currentCode">
        <input name="currency" type="text" placeholder="Currency" ng-model="currentCurrency">
    </div>
</div>

JS

function Ctrl($scope) {

    $scope.countries = [
    { country: "Sweden",  currency: "SEK", countryCode: "SE" },
    { country: "USA", currency: "USD", countryCode: "US" },
    { country: "Canada", currency: "CAD", countryCode: "CA" }
  ];


    $scope.updateVals = function() {
        if ($scope.currentItem) {
          $scope.currentCurrency = $scope.currentItem.currency;
            $scope.currentCode = $scope.currentItem.countryCode;
        } else {
            $scope.currentCurrency = undefined;   
            $scope.currentCode = undefined;
        }
    }

}

它在這里工作: http : //jsfiddle.net/U3pVM/18965/

更新了小提琴以使所有內容變得更短:

http://jsfiddle.net/sx7xnoyr/1/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM