所以我有这个数组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/