所以我有这个数组人
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
,但这不会使选择多个元素中的选择“突出显示”。我知道有更实用的方法可以做到这一点,但我想弄清楚如何使用选择倍数。
答案 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
数组不同。
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
。