视图中有三个复选框,用于更改 $scope.colorChoice 的三个值的状态。
我想编写一个函数,将每种真实颜色与 JSON 列表中的相应颜色进行比较。如果一个人的数组中至少有一种颜色已被检查为 true,应显示人员姓名。
如何编写这样的函数?
到目前为止,我已经走了这么远:
JSON列表:
[
{
"name": "kevin",
"colors": ["red, green"]
},
{
"name": "hans",
"colors": ["green"]
},
{
"name": "jolene",
"colors": ["red, blue"]
},
{
"name": "peter",
"colors": ["blue"]
}
]
复选框:
<label ng-repeat="(item,enabled) in colorChoice">
<input type="checkbox" ng-model="colorChoice[item]">
</label>
控制器:
$scope.colorChoice = {
red: false,
green: false,
blue: false
};
例如:
$scope.colorChoice = {
red: true,
green: false,
blue: true
};
。将显示:凯文、乔琳、彼得·
感谢您的帮助!
文
你可能想研究的一件事是角度清单模型,
http://vitalets.github.io/checklist-model/
这不会解决您的问题,因为我看到您已经在处理它将为您处理的问题。不过,我发现它非常干净,可以用于像您这样的目的。
使用colorChoice对象,无论您是否使用角度清单模型,您都可以执行以下操作:
.HTML
<ul>
<li ng-repeat='person in people | filter: colorFilter'>{{person.name}}</li>
</ul>
控制器滤波功能
$scope.colorFilter = function(person) {
for (var i = 0; i < person.colors.length; i++) {
var color = person.colors[i];
if ($scope.colorChoice[color] == true)
return true;
}
return false;
};
我喜欢将这样的角度过滤器与返回 true 或 false 的函数一起使用。在这种情况下,它们可以非常通用。角度过滤器导轨
谢谢凯尔 - 清单模型看起来很有趣。
我现在想出了以下解决方案:
首先是一个小助手函数来过滤掉所有激活的复选框:
$scope.colorChoiceTrue = function () {
var result = [];
for (var key in $scope.colorChoice) {
if ($scope.colorChoice[key] === true) {
result.push(key);
};
};
return result;
}
另一个用于搜索数组中字符串的辅助函数:
$scope.searchStringInArray = function (str, strArray) {
for (var j = 0; j < strArray.length; j++) {
if (strArray[j].match(str)) return true;
}
return false;
}
最后,此函数返回至少具有一种颜色与 colorChoice 匹配的每个人:
$scope.peopleSelected = function () {
var result = [];
angular.forEach($scope.people, function (entry, key) {
if ($scope.searchStringInArray(entry.color, $scope.colorChoiceTrue())) {
result.push(entry.name);
};
});
return result;
};