ng-repeat 共享相同 ng-model 的 ng-options

ng-repeat over ng-options that share the same ng-model

我知道这很奇怪。如果这不可能,我将转换 API 数据。

但是,我需要多个下拉菜单共享同一个 ng-model。

问题:

  1. 为什么 ng-model 具有相同的 var 名称时是唯一的?
  2. 如何让每个下拉菜单共享一个 ng-model="selectedSize"

    <div ng-repeat="(key, val) in listing.colors_and_sizes.data" >
    <p>{{selectedSize}}</p>
     <input
        ng-checked="selected"
        type="radio"
        name="colors"
        ng-model="selected.pdw.color"
        ng-value="key"/>
    
    <select ng-model="selectedSize"
            ng-options="choice as choice for (idx, choice) in val.sizes.split(',')"
            ng-change="selected.product.set.size(key,val, selectedSize);">
            <option value="">Please select a size</option>
    </select>
    
    </div>
    

ng-repeat 创建一个子作用域,因此 selectedSize 是该子作用域上的 属性,因此每个子作用域都有自己的选择。 Read this answer related to child scope inheritance and how it applies to various directives。如果你想共享相同的ng-model,你只需要在你的控制器上定义一个范围属性。 例如:-

 $scope.size = {};

并将您的 ng-model 设置为 ng-model="size.selectedSize":

<select ng-model="size.selectedSize"
        ng-options="choice as choice for (idx, choice) in val.sizes.split(',')"
        ng-change="selected.product.set.size(key,val, size.selectedSize);">
        <option value="">Please select a size</option>
</select>

您不需要传递 size.selected 它也可以在您的控制器中使用,但传递它也没有坏处。