![](/img/trans.png)
[英]Make field required based on another value (state required if country is USA)
[英]angular: how do I make a dependent required field country->state?
我有一個野外國家。 列表中的某些國家(例如美國或加拿大)被划分為州。 選擇了這些國家后,將出現第二個選擇並且是必需的。
HTML:
<label>Country*</label>
<select name="country" class="gu3" ng-model="companyCriteria.country" ng-options="country.label for country in countries" required=""></select>
<div class="row" ng-show="stateAvailable">
<label>Province*</label>
<select name="state" class="gu3" ng-model="companyCriteria.state" required="">
<option ng-repeat="state in states" value="{{state.code}}">{{state.label}}</option>
</select>
</div>
控制器:
app.controller('CompanyController', function ( $scope, companies , Countries, States ... ) {
//...
$scope.countries = Countries;
$scope.states = [];
$scope.stateAvailable = false;
$scope.$watch( 'companyCriteria.country', function( after, before ) {
if ( searchCompanyCriteria.country && searchCompanyCriteria.country.div ) {
$scope.states = States.get( after.code );
$scope.stateAvailable = true;
} else {
$scope.states = [];
$scope.stateAvailable = false;
}
} );
$scope.search = function () {
if ( !$scope.companyForm.$valid ) return; //Returns when states are hidden
//Do search ...
};
問題是隱藏狀態選擇時$ scope.companyForm。$ valid為false。 我不確定如何繼續以一種有角度的優雅方式對其進行編碼(而不必通過jQuery的方式破解dom)。
注意:Angular v1.2.0-rc.3
您可以使用ng-required
來解析角度表達式並將字段設置為必填:
<label>Country*</label>
<select name="country" class="gu3" ng-model="companyCriteria.country" ng-options="country.label for country in countries" required=""></select>
<div class="row" ng-show="stateAvailable">
<label>Province*</label>
<select name="state" class="gu3" ng-model="companyCriteria.state" ng-required="companyCriteria.country">
<option ng-repeat="state in states" value="{{state.code}}">{{state.label}}</option>
</select>
</div>
如果國家/地區設置了值,則僅需要州。 但是,您可以在此處放置任何作用域表達式(因此,如果您要調用返回布爾值的控制器函數,也可以使用)。
ng-required
的文檔在這里 。
而不是ng-show
使用ng-if
(假設您使用的是Angle 1.1.5或更高版本):
<div class="row" ng-if="stateAvailable">
<label>Province*</label>
<select name="state" class="gu3" ng-model="companyCriteria.state" required>
<option ng-repeat="state in states" value="{{state.code}}">{{state.label}}</option>
</select>
</div>
或者,只需使用ng-required
:
<select name="state" ng-model="companyCriteria.state" ng-required="stateAvailable">
<option ng-repeat="state in states" value="{{state.code}}">{{state.label}}</option>
</select>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.