如何在 angularjs 中填充 html select 元素选项?

how to populate html select element options in angularjs?

我需要用美国所有州填充 html select 选项。如果我能看到一个例子,那将会很有帮助。我是否需要在范围变量中定义所有状态?

谢谢!

是的,最好的方法是将它作为范围变量存储在对象数组中,然后在您的模板中使用它。

像这样....

假设 $scope.allState[] 是美国所有州的对象数组。

然后在您的模板中尝试将其作为...

<select type="text" name="name" id="name"  
                    data-ng-model="formData.state"
                  ng-options="state for state in allState"
                    required >
                        <option value="">Select</option>
                    </select>

一点也不,不需要在范围内单独定义所有状态。你可以在 angular js 中简单地使用 $watch 服务。

please refer the jsfiddle link here:

州和城市可以放在对象数组中,data-ng-options 用于显示将从控制器加载的选项。 $watch 将监视状态的变化并相应地加载城市。

function Controller($scope) {

    var states = [{
         "Name": "karnataka",
            "cities": [{
          
                "Name": "bangalore"
        }, {
         
                "Name": "mangalore"
        }, {
           
                "Name": "mysore"
        }]
    }, {
     
            "Name": "maharashtra",
            "cities": [{
           
                "Name": "Mumbai"
        }, {
           
                "Name": "pune"
        }, {
          
                "Name": "nagpur"
        }]
    }];

    $scope.groups = states;
    $scope.currentGroup = states[0];
    $scope.currentItems = $scope.currentGroup.cities;
    $scope.currentItem = $scope.currentItems[0];
    
    $scope.$watch('currentGroup', function () {
          $scope.currentItems = $scope.currentGroup.cities;
          $scope.currentItem = $scope.currentGroup.cities[0];
      }); 
    }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<section ng-app ng-controller="Controller">
 
    
        <div class="span4">
            <label for="cboGroup">States</label>
    <select data-ng-model="currentGroup" data-ng-options="group.Name for group in groups"></select>
        </div>
        <div class="span4">
            <label for="cboItem">Cities</label>
    <select data-ng-model="currentItem" data-ng-options="item.Name for item in currentItems"></select>
        </div>
   <div>
       Selected city :  {{currentItem.Name}}
   <div>
</section>