javascript - 选择影响其填充对象的属性的多个元素

标签 javascript angularjs ng-options

所以我有这个数组people

people = [{name: "John",hair: false},{name: "James": hair: false}]

我有一个 select 元素,它的 multiple 属性是从

填充的
 <select ng-model="people" multiple
         ng-options="person.hair as person.name for person in people">
 </select>

我想要实现的是,当用户从此选择元素中选择一个或多个项目时,它会将所选项目的头发属性设置为 true

现在发生的事情是我选择一个项目并将 people 设置为 false,这是有道理的。选择需要 ng-model 才能使 ng-options 工作。如果我将它设置为其他内容,people

不会有任何改变

我试过在 ng-change 中放置一个函数,并抛出我设置的 ng-model 但这不会使选择“突出显示”选择多个元素。我知道有更多实用的方法可以做到这一点,但如果可以的话,我想弄清楚如何使用选择倍数。

最佳答案

这是一种方法:

<select ng-model="hairyPersons" multiple
        ng-change="updatePeople(hairyPersons)"
        ng-options="person as person.name for person in people">
</select>
$scope.updatePeople = function(selects) {
    $scope.people.forEach(x => x.hair=false);
    selects.forEach(x => x.hair=true);
};

ng-model 变量需要不同于 ng-options 数组。

The DEMO

angular.module("app",[])
.controller("ctrl", function($scope) {
  $scope.people = [
    {name: "John", hair: false},
    {name: "James", hair: false},
    {name: "Mary", hair: false},
    {name: "Fred", hair: false},
  ];
  $scope.updatePeople = function(selects) {
    $scope.people.forEach(x => x.hair=false);
    selects.forEach(x => x.hair=true);
  };
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl">
     <select ng-model="hairyPersons" multiple
         ng-change="updatePeople(hairyPersons)"
         ng-options="person as person.name for person in people">
     </select>
     <div ng-repeat="p in people">
       {{p.name}} hair={{p.hair?'TRUE':false}}
     </div>
     <h3>hairyPersons</h3>
     <ol>
       <li ng-repeat="h in hairyPersons">{{h.name}}</li>
     </ol>
</body>


另一种方法是使用复选框列表:

<div ng-repeat="p in people">
    <input type="checkbox" ng-model="p.hair">{{p.name}}<br>
</div>

ng-model 指令直接对 people 数组中的对象进行操作。

所有未选中的框设置hair: false;所有选中的框都在各自的对象上设置了 hair: true

关于javascript - 选择影响其填充对象的属性的多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51867610/

相关文章:

javascript - 按升序和降序对具有ID的DIV进行排序

javascript - 无法获取 Uint8Array 字节

javascript - Thinkster 教程上的 AngularJS

javascript - 使用 Angular JS 让图像出现在弹出窗口中

angularjs - 带有对象数据源的 ng-options

angularjs - 编写自定义指令以将工具提示添加到 AngularJS (TypeScript) 中的 ng-options

javascript - JS 最佳实践和安全检查用户的值,而不会出现未定义的情况 - 使用迷你函数

javascript - Bootstrap-Datepicker 无法获取日期?

javascript - AngularJS View 不更新

javascript - 查找 ng 重复中选择的选项