Angularjs show select box dependent another select box

时间:2015-07-31 19:24:22

标签: angularjs

I am using AngularJS 1.3.

In a form with 3 select boxes, from the choosen option of the first one i will show only south or only north select box.

In my try below i got erros like completely disappear the content below.

Wich will be the best way using angularjs to show only one of the two boxes ?

<select name="Type" ng-model="data.Type">
  <option value="2">South</option>
  <option value="3">North</option>             
</select>

<div ng-if="data.Type==3">
  <label class="item item-input item-select" >
    <div class="input-label">North</div>
      <select name="South" ng-model="data.South">
          <option value="1">Dallas</option>
          <option value="2">Miami</option>
      </select>
  </label>
</div>

<div ng-if="data.Type==2">
  <label class="item item-input item-select" >
    <div class="input-label">South</div>
      <select name="North" ng-model="data.North">
        <option value="1">New York</option>
        <option value="2">Boston</option>
      </select>
  </label>
</div>

1 个答案:

答案 0 :(得分:1)

Works for me as-is with a very basic controller (see fiddle).

angular.module('app', [])
.controller('someController', function($scope) {
    $scope.data = {} 
});

The reason you only see one dropdown defaulted to blank is that there is not an initial value specified for the ng-model in this case data.Type. But it does work as in the 'North' and 'South' values are also there and selecting one of them causes the next dropdown to appear.

If you initialise data.Type to '2' in the controller then the dropdown will be defaulted to 'South' and one of the other dropdowns will appear.

You may also want to set initial values for data.North & data.South.

Fiddle with those updates

angular.module('app', [])
.controller('someController', function($scope) {
    $scope.data = {
        'Type' : 2,
        'South' : 1,
        'North' : 1
    };
});