我正在构建一个Angular / Javascript / Ionic / Cordova应用程序。
我有一个函数,我调用下面的数组,它存储为变量(existingEntries)
categories: Array [276]
[0...99]
0: Object
id: 288
exclude: false
1: Object
id: 320
exclude: true
此函数会抓取该数组中的所有元素,以查看值exclude是否设置为true或false
var existingEntries = $scope.categoryList;
if(existingEntries == null) existingEntries = [];
for (var i = 0; i < existingEntries.length; i++) {
if (existingEntries[i]['exclude'] == true) {
$scope.addLocalExcludedCategories(i);
} else if (existingEntries[i]['exclude'] == false) {
$scope.removeLocalExcludedCategories(i);
}
}
完成此操作后,将调用其他相关函数(addLocal ..并删除Local ...)来存储id。下面是addLocal ..函数,这可以工作,但是当我反复运行这些代码时,我得到了重复,我相信它可以更好地编码。我正在使用localstorage,因为我需要在本地保存数组,但如果你有其他解决方案会很棒。
$scope.addLocalExcludedCategories = function(catID) {
console.log("addLocalExcludedCategories Called")
//Add Item to Excluded Categories Variable
var existingEntries = JSON.parse(window.localStorage.getItem("ExcludedCategories"));
if(existingEntries == null) existingEntries = [];
var entryId = catID;
var entry = {
'id': entryId,
};
existingEntries.push(entry);
window.localStorage.setItem("ExcludedCategories", JSON.stringify(existingEntries));
$scope.ExcludedCategories = window.localStorage.getItem("ExcludedCategories");
}
此处还有删除功能,因为我找到了将排除值设置为true而不是false的id,因此无法正常工作。
$scope.removeLocalExcludedCategories = function(catID) {
console.log("removeLocalExcludedCategories Called")
//Remove Item to Excluded Categories Variable
var existingEntries = JSON.parse(window.localStorage.getItem("ExcludedCategories"));
if(existingEntries == null) existingEntries = [];
for (var i = 0; i < existingEntries.length; i++) {
if (existingEntries[i]['id'] == catID) {
console.log(i);
existingEntries.splice(i, 1);
}
}
//console.log("Remove Categories >>>");
//console.log(existingEntries);
window.localStorage.setItem("ExcludedCategories", JSON.stringify(existingEntries));
$scope.ExcludedCategories = window.localStorage.getItem("ExcludedCategories");
console.log($scope.ExcludedCategories);
}
希望这有意义,并提前感谢!
答案 0 :(得分:1)
您没有检查 existingEntries 数组中是否已存在条目,这就是您获取欺骗的原因 试试此代码......
$scope.addLocalExcludedCategories = function(catID) {
console.log("addLocalExcludedCategories Called")
//Add Item to Excluded Categories Variable
var existingEntries = JSON.parse(window.localStorage.getItem("ExcludedCategories")) || [];
var entryId = catID;
var entry = {
'id': entryId,
};
if(existingEntries.length > 0){
existingEntries.forEach(function(entry){
if(entry.id !== entry.id){
existingEntries.push(entry);
}
});
答案 1 :(得分:0)
使用ng-if语句计算出来,然后在本地存储数组,然后在调用时解析它。
$scope.ifCatExcludedTerms = function(sent_id){
var doesNotExist = true;
arraytosearch = JSON.parse(localStorage.getItem("categoryListMem"));
//console.log (sent_id);
for (var i = 0; i < arraytosearch.length; i++) {
if (arraytosearch[i]['id'] == sent_id) {
doesNotExist = false;
}
}
return doesNotExist;
}