繁体   English   中英

角:如何使一个依赖字段必填国家->状态?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM