0

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

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 为假。我不知道如何继续以有角度和优雅的方式对其进行编码(而不必以 jquery 方式破解 dom)。

注意:Angular v1.2.0-rc.3

4

2 回答 2

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这里

于 2013-11-08T12:33:37.317 回答
2

而不是ng-show使用ng-if(假设您使用的是 angular 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>
于 2013-11-08T12:35:19.903 回答