【问题标题】:default selected items dynamically in several options in angular在角度的几个选项中动态默认选定的项目
【发布时间】:2014-12-20 01:25:06
【问题描述】:

我在这里看到了https://docs.angularjs.org/api/ng/directive/select 的示例,这有 3 个具有相同值的选择,我如何在我的选项中选择不同的值?

我有这个:

    <li ng-repeat="tarea in tareas">
      <input type="checkbox" ng-model="tarea.COMPLETADA" ng-change="updTarea(tarea.ID)"/>
      <span class="done-{{tarea.COMPLETADA}}" >{{tarea.NAME}} {{tarea.CLASIFICADORES}}</span>
      <select ng-model="selectedOpt" 
      ng-options="clasificador.NAME for clasificador in clasificadores">
      </select>
      <button class="buttons delete right" ng-click="delTarea(tarea.ID)"> Eliminar</button>
    </li>

所以我可以有 5,10,15 个选项,并且我想用我在 tarea.CLASIFICADORES 中的值制作一个选定的项目,我尝试了这个

$scope.selectedOpt = $scope.clasificadores[1]

但这会使所有选项都具有相同的值,就像示例中一样...

如何使用我在每个项目中的 ng-repeat 中的值动态地在选项中创建不同的选定项目?

我用 ajax 加载数据...

我的问题是使用 tarea.CLASIFICADORES 设置默认选定项目。例如,我有一个包含分类器的待办事项列表,我希望我的 ng-options 在页面加载时默认选择我的数据库值分类器

【问题讨论】:

    标签: javascript angularjs select options ng-options


    【解决方案1】:

    问题是,您对所有选择使用相同的范围变量。您也可以像这样将选定的选项存储在数组中:

    function TestCtrl($scope) {
      $scope.items = [
        { id: 1, class: 1 },
        { id: 2, class: 2 },
        { id: 3, class: 1 },
      ];
      $scope.classes = [
        { name: "class 1", id: 1},
        { name: "class 2", id: 2},
        { name: "class 3", id: 3}
        ];
      };
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <div ng-app>
      <div ng-controller="TestCtrl">
        <div ng-repeat="currentItem in items">
          <select ng-model="selectedClass[$index]" ng-init="selectedClass[$index]=(classes|filter:{id: currentItem.class})[0]" ng-options="class.name for class in classes track by class.id" >
          </select>
          selected class: {{selectedClass[$index]}}
        </div>
      </div>
    </div>

    在本例中,我使用了由 ng-repeat 指令设置的变量 $index。顾名思义,它包含重复循环的当前索引。

    更新

    我更新了代码-sn-p,因此它为每个选择输入设置了默认值。

    不同的项目现在包含一个带有相应类 id 的字段。我用ng-init 初始化选择输入。使用此指令,我设置了selectedClass[$index],这是当前项目的选定值。由于我们只有 class-id 作为项目的属性,因此我使用过滤器查找 ID 为 (classes|filter:{id: currentItem.class})[0] 的相应类对象

    要摆脱过滤器,您只需将每个项目的类设置为完整的类对象而不是 id。

    【讨论】:

    • 我觉得我没有解释好,我的问题是用tarea.CLASIFICADORES设置默认选中项。例如,我有一个包含分类器的待办事项列表,我希望我的 ng-options 在页面加载时默认选择我的数据库值分类器
    • 我已经更新了我的答案。现在它设置不同选择元素的默认值。我希望我现在完全理解了你的问题......
    • 这不能解决我的问题,我在其他示例中看到了你的答案,但在我的情况下不起作用,我解决了这个问题:
    • 感谢您的帮助
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签