angular:如何创建依赖的必填字段country-> state?

时间:2013-11-08 12:27:29

标签: angularjs

我有一个野外国家。列表中的一些国家(如美国或加拿大)分为州。选择此类国家/地区后,将出现第二个选择,并且是必需的。

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方式)。

注意:Angular v1.2.0-rc.3

2 个答案:

答案 0 :(得分:2)

您可以使用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的文档是here

答案 1 :(得分:2)

而不是ng-show使用ng-if(假设您使用的角度为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>