我有一個地址的表單。我收集的第一個地址字段是郵政編碼。輸入郵政編碼後,自定義指令將查詢外部API並獲取包含城市,州,縣和州內所有縣的列表的對象。將選項填充到選擇使用基於AngularJS的另一個字段的輸入的數據
在郵政編碼字段中,我分配給城市,州和縣輸入字段的模型中有屬性傳遞。該指令採用這些指令並填充scope
變量,以使每個變量的值同步。
我的問題是在縣選擇框。我需要首先填寫該州所有縣的列表(同樣,所有可用的選項都由API響應給出)。一旦該字段已填充,我需要設置值。
設置很簡單。有用。我無法弄清楚我的生活如何使用可用選項填充字段。
- 我不能使用元素ID,因爲我需要這個指令可以重複使用這個表單中的多個地址。
- 我不能使用ng-options,至少在我的視圖中是這樣,因爲在輸入郵政編碼之前我沒有填充數據。
這裏是我的形式的小片段,顯示了郵政編碼和縣字段:
<div class="form--row">
<div class="form--col5">
<label class="form--label" for="nbZip">Zip</label>
<input
id="nbZip"
class="form--input"
type="text"
ng-model="data.ClientDetails.zip"
ng-required="data.Client == 'true'"
blur="update()"
ziplookup
zip-city="data.ClientDetails.city"
zip-state="data.ClientDetails.state"
zip-county="data.ClientDetails.county"
>
</div>
<!-- First Client NB County -->
<div class="form--row">
<div class="form--col5">
<label class="form--label" for="nbCounty">County</label>
<select class="form--input" id="nbCounty" ng-model="data.ClientDetails.county" ng-required="data.Client == 'true'" change="update()">
<!-- generate county list! -->
</select>
</div>
</div>
我的指令:(郵編是一個定製的服務,我注入指令)
directives.directive(
'ziplookup',
['ZipCode',
function (ZipCode) {
var scope
, element
, zipData;
var getZipData = function (event) {
// When this function is called, `this` is
// bound to the scope matching the element.
scope = this;
// We also get access to the element itself.
element = $(event.target);
ZipCode
// Shoot off our call for the location data,
// using the value in the `<input>`.
.getLocationData(element.val())
// When data is returned, we will set the
// returned data.
.then(setZipData)
// Update the view with the returned data.
.then(updateCity)
.then(updateState)
.then(updateCounty)
};
var setZipData = function (data) {
// This function makes the scope and data
// accessible from the `update___` functions
// that follow.
// We'll set `zipData` to the returned data.
zipData = data.data;
};
var updateCity = function() {
scope.city = zipData.city;
};
var updateState = function() {
scope.state = zipData.state;
};
var updateCounty = function() {
scope.county = zipData.county;
};
var link = function (scope, elem) {
elem.bind('blur', angular.bind(scope, getZipData));
};
return {
restrict: 'A',
scope: {
city: '=zipCity',
state: '=zipState',
county: '=zipCounty'
},
link: link
};
}]);