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

时间:2018-08-15 23:08:32

标签: javascript angularjs ng-options

所以我有这个数组

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>

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

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

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

1 个答案:

答案 0 :(得分:1)

这里是一种方法:

<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