This question already has answers here:
Working with select using AngularJS's ng-options
                            
                                (8个答案)
                            
                    
                5年前关闭。
        

    



如何在占位符ng-options创建的空白选项中添加占位符文本。我希望下拉菜单的空白选项说“请选择尺寸”

警告:
*注意:这是一个额外的怪异原因,因为我不是将其作为数组,所以我将size集合作为split(',')*

Live Code Fiddle

HTML:

<form ng-app="app" ng-controller="Ctrl">
    <div class="color-pick" ng-repeat="(key, val) in productData.colors_and_sizes.data">
        <input type="radio" name="colors" ng-model="$parent.myColor" ng-value="key" />
        <img ng-click="$parent.myColor = key" ng-src="{{val.swatch_image}}" alt="">{{key}}
        <div class="size-pick" ng-show="$parent.myColor==key">
            <select ng-model="$parent.mySize" ng-options="size for size in val.sizes.split(',')"></select>
        </div>
    </div>
    myColor: {{myColor}}<br/>
    mySize: {{mySize}}
</form>


JS:

var app = angular.module("app", []);

app.controller('Ctrl', function ($scope, $filter, $http) {
 $scope.productData = {
  "colors_and_sizes": {
    "data": {
      "Black": {
        "swatch_image": 'http://lorempixel.com/50/50',
        "sizes": "X Small, Small, Medium, Large, Xlarge, XX Large"
      },
      "Blue": {
        "swatch_image": 'http://lorempixel.com/50/50',
        "sizes": "X Small, Small, Medium, Large, Xlarge, XX Large"
      }
    }
  }
};

});

最佳答案

请在这里查看http://jsfiddle.net/jg42xsop/
有人说我们应该使用ng-init而不是$ parent

<form ng-app="app" ng-controller="Ctrl">
    <div class="color-pick" ng-repeat="(key, val) in productData.colors_and_sizes.data" ng-init="item = this">
        <input type="radio" name="colors" ng-model="item.myColor" ng-value="key" />

        <img ng-click="item.myColor = key" ng-src="{{val.swatch_image}}" alt="">
            <p>{{key}} </p>

            <div class="size-pick"  ng-show="item.myColor==key">
            <select ng-model="item.mySize" ng-options="size for size in val.sizes.split(',')">
                 <option value="">Please choose a size</option>
            </select>

            </div>

            <p>  myColor: {{myColor}}</p>
            <p> mySize: {{mySize}} </p>
            <hr/>
        </div>
</form>

10-06 15:04