How do I optimize filtering in AngularJS? - angularjs

I have here a filter for AngularJS. Is there any better way for this?
return function (data, selected) {
var result = [];
if (selected[0] == 'All Types') {
result = data;
}
else {
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < selected.length; j++) {
if (data[i].Type == selected[j]) {
result.push(data[i]);
}
}
}
}
return result;
};

return function (data, selected) {
var result = [];
if (selected[0] == 'All Types') {
result = data;
}
else {
result=data.filter(x=>selected.indexOf(x.Type)>-1);
}
return result;
};

Obviously this is using lodash, but native methods can be substituted:
return (data, selected) => {
return
_.first(selected) === 'All Types' ? data :
_.reduce(data, (sum, value, key) => {
if (_.includes(selected, value.Type)) {
sum.push(value);
}
return sum;
}, []);
}

Use data for selected value. I am assuming selected value is in data[i].selected.
return function (data) {
var result = [];
if (data[0].selected == 'All Types') {
result = data;
}
else {
for (var i = 0; i < data.length; i++) {
if (data[i].Type == data[i].selected) {
result.push(data[i]);
}
}
}
return result;
};
We can use filters
return function (data) {
if (data[0].selected == 'All Types') {
return data;
}
else {
return data.filter(function (item) {
return item.Type == item.selected;
});
}
};

Related

problems with ng-show angularjs

ng-show did not work clearly for me in angular js.
this is the "loading" div:
<div class="loader" ng-show="vm.loadingNotifications" ng-cloak>loading...</div>
and that's the API call in the controller:
function getNotifications(userId) {
if (vm.generalNotifications.length > 0) {
vm.loadingNotifications = false;
} else {
vm.loadingNotifications = true;
$.ajax({
type: 'GET',
url: AppConfig.apiUrl + 'Notifications/GetAllNotificationsByUserId?userId=' + userId,
success: function (notifications) {
if (notifications) {
$("#all-not").addClass("active");
if (notifications.length > 0) {
let tempNotifications = [];
for (let j = 0; j < notifications.length; j++) {
let element = notifications[j];
let title = getSpecificConst(element.NotificationTitle)
element.NotificationTitle = title;
let text = getSpecificConst(element.NotificationText)
element.NotificationText = text;
tempNotifications.push(element);
}
vm.generalNotifications = sortArray(tempNotifications);
vm.displayedNotifications = sortArray(tempNotifications);
vm.isEmptyNotifications = false;
}
else {
vm.isEmptyNotifications = true;
}
} else {
vm.isEmptyNotifications = true;
}
vm.loadingNotifications = false;
}
});
}
}
the VM loading is updating clearly, but the ng-show stack always in true.
you need to use AngularJS Scope on the controller.
$scope.vm = {
generalNotifications:[],
loadingNotifications: false,
....
};
function getNotifications(userId) {
if ($scope.vm.generalNotifications.length > 0) {
$scope.vm.loadingNotifications = false;
} else {
$scope.vm.loadingNotifications = true;
.....
}

how to apply filter functionality on a particular trees node rather on the whole tree

I am searching for compName-1 in the search box. It is returning all the repos in which this compName-1 string is found.
I dont want the search option to search in all the repos. I want it to search in particular repo which is checked. Is there any way to achieve it?
Please find my problem in this plunker. https://plnkr.co/edit/iCOiJDjeP8httwnf2c0t?p=preview
Controller.js
var app = angular.module('testApp', []);
app.controller('treeTable', ['$scope', '$http', function ($scope, $http) {
$scope.list = [];
$scope.list.push({name: "repo 1", version:"0.0", size:"0", description:" ", label: "", date: "XXX", id:"repo1"});
$scope.list.push({name: "repo 8", version:"0.0", size:"0", description:" ", label: "", date: "XXX", id:"repo2"});
$scope.list.push({name: "repo 7", version:"0.0", size:"0", description:" ", label: "", date: "XXX", id:"repo3"});
$scope.displayChildren = function(item, id) {
console.log(item.showTree);
item.showTree = !item.showTree;
console.log(id);
if(id === 'repo'+1) {
if(!(item.children && item.children.length > 0)) {
$http.get("List_repo1.json")
.then(function(response) {
console.log('response repo1');
item.children = response.data.response.repoBundles;
item.showTree = true;
});
}
}
if(id === 'repo'+2) {
if(!(item.children && item.children.length > 0)) {
$http.get("List_repo2.json")
.then(function(response) {
console.log('response repo2');
item.children = response.data.response.repoBundles;
item.showTree = true;
});
}
}
if(id === 'repo'+3) {
if(!(item.children && item.children.length > 0)) {
$http.get("List_repo3.json")
.then(function(response) {
console.log('response repo3');
item.children = response.data.response.repoBundles;
item.showTree = true;
});
}
}
};
$scope.toggleChildren = function(item, parentItem) {
console.log(parentItem);
if(parentItem !== void 0) {
if(parentItem.bundles !== void 0) {
$scope.$emit('changeBundles', parentItem);
} else if(parentItem.item.children !== void 0) {
console.log('parent child');
$scope.$emit('changeParent', parentItem);
}
}
if (item.children !== void 0) {
console.log(item.children);
console.log('inside children');
$scope.$broadcast('changeChildren', item);
} else if(item.components !== void 0){
console.log(item + 'inside comp');
$scope.$broadcast('changeComponents', item);
}
};
$scope.toggleAllCheckboxes = function ($event) {
var i, item, len, ref, results, selected;
selected = $event.target.checked;
if(selected) {
$scope.selectedCheckbox = false;
} else {
$scope.selectedCheckbox = true;
}
ref = $scope.list;
results = [];
for (i = 0, len = ref.length; i < len; i++) {
item = ref[i];
item.selected = selected;
if (item.children != null) {
results.push($scope.$broadcast('changeChildren', item));
} else {
results.push(void 0);
}
}
return results;
};
$scope.$on('changeChildren', function (event, parentItem) {
var child, i, len, ref, results;
ref = parentItem.children;
results = [];
console.log(ref === void 0);
for (i = 0, len = ref.length; i < len; i++) {
child = ref[i];
child.selected = parentItem.selected;
console.log("child" + child);
if (child.components != null) {
console.log("inside if " + child.components);
results.push($scope.$broadcast('changeComponents', child));
} else {
results.push(void 0);
}
}
return results;
});
$scope.$on('changeComponents', function (event, parentItem) {
var child, i, len, ref, results;
ref = parentItem.components;
results = [];
console.log(parentItem.selected);
for (i = 0, len = ref.length; i < len; i++) {
child = ref[i];
child.selected = parentItem.selected;
console.log("child" + child.selected + child.value);
}
});
$scope.$on('changeParent', function (event, parentScope) {
var children;
children = parentScope.item.children;
parentScope.item.selected = $filter('selected')(children).length === children.length;
parentScope = parentScope.$parent.$parent;
if (parentScope.item != null) {
return $scope.$broadcast('changeParent', parentScope);
}
});
$scope.$on('changeBundles', function (event, parentScope) {
var children;
children = parentScope.bundles.components;
parentScope.bundles.selected = $filter('selected')(children).length === children.length;
parentScope = parentScope.$parent.$parent;
if (parentScope.item !== null) {
return $scope.$broadcast('changeParent', parentScope);
}
});
}]);
app.filter('selected', [
'$filter',
function ($filter) {
return function (files) {
return $filter('filter')(files, { selected: true });
};
}
]);

How to sort an arraylist by multiple fields in Typescript

How can I sort an arraylist in Typescript by multiple fields.
For example, I have this object:
enter image description here
My single sort method works fine:
private sortFunction(a: RSFolderObject, b: RSFolderObject) {
var a_label = a.label.toLowerCase();
var b_label = b.label.toLowerCase();
if (a_label < b_label) {
return -1;
} else if (a_label > b_label) {
return 1;
} else {
return 0;
}
}
For multiple sorting I used that:
private sortFunction(a: RSFolderObject, b: RSFolderObject) {
var a_label = a.label.toLowerCase();
var b_label = b.label.toLowerCase();
var a_description = a.description[0].toLowerCase().replace("\\", "");
var b_description = b.description[0].toLowerCase().replace("\\", "");
if (a_label < b_label || a_description < b_description) {
return -1;
} else if (a_label > b_label || a_description > b_description) {
return 1;
} else {
return 0;
}
}
But it does not work.
OK, I solved it like this:
private sortFunction(a: RSFolderObject, b: RSFolderObject) {
var a_label = a.label.toLowerCase();
var b_label = b.label.toLowerCase();
var a_description = a.description[0].toLowerCase().replace("\\", "");
var b_description = b.description[0].toLowerCase().replace("\\", "");
if (a_label < b_label) {
return -1;
}
else if (a_label > b_label) {
return 1;
}
else {
if (a_description < b_description) {
return -1;
}
else if (a_description > b_description) {
return 1;
}
else {
return 0;
}
}
}

Unique after filter Angular

So I've been trying to figure this out for a while but it's still stumping me.
Ultimately I want to be able to do the following
object in objects | unique:'DateTime | limitTo:4'//As the year is the first 4 characters
(oh well y10k :))
But I don't know how I'd write that, I'd prefer to have it be inline html code so I don't need to mess around with dependency injection.
Thanks in advance!
Use this derictive:
.filter('unique', function () {
return function (items, filterOn) {
if (filterOn === false) {
return items;
}
if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
var hashCheck = {}, newItems = [];
var extractValueToCompare = function (item) {
if (angular.isObject(item) && angular.isString(filterOn)) {
return item[filterOn];
} else {
return item;
}
};
angular.forEach(items, function (item) {
var valueToCheck, isDuplicate = false;
for (var i = 0; i < newItems.length; i++) {
if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
newItems.push(item);
}
});
items = newItems;
}
return items;
};
});

AngularJS Property Bag

Is there a formal property bag for Angular? I need a way to temporarily store variables and optionally save them between apps.
To save time, I whipped one up. It's here if anyone needs it, however I would love to find one in a framework that is supported by a team:
/**
* Created by Fred Lackey on 4/24/15.
*/
(function (module) {
var propertyBag = function (localStorage) {
var items = [];
var getIndex = function (key) {
if (!key || !key.trim || key.trim().length < 1) { return -1; }
if (items.length < 1) { return -1; }
for (var i = 0; i < items.length; i += 1) {
if (items[i].key.toLowerCase() === key.toLowerCase()) { return i; }
}
return -1;
};
var exists = function (key) {
return (getIndex(key) >= 0);
};
var getItem = function (key) {
var index = getIndex(key);
return (index >= 0) ? items[index] : null;
};
var getValue = function (key) {
var index = getIndex(key);
return (index >= 0) ? items[index].value : null;
};
var putItem = function (key, value) {
if (!key || !key.trim || key.trim().length < 1) { return; }
var index = getIndex(key);
if (index >= 0) {
items[index].value = value;
} else {
items.push({ key: key, value: value });
}
};
var removeItem = function (key) {
var index = getIndex(key);
if (index >= 0) { items.splice(index, 1); }
};
var count = function () {
return items.length;
};
var saveBag = function (key) {
if (!key || !key.trim || key.trim().length < 1) { return; }
localStorage.add(key, items);
};
var loadBag = function (key) {
if (!key || !key.trim || key.trim().length < 1) { return; }
var bag = localStorage.get(key);
if (!bag || !bag.length) { return; }
for (var i = 0; i < bag.length; b += 1) {
if (!bag[i].key || !bag[i].key.trim || bag[i].key.trim().length < 1) { continue; }
putItem(bag[i].key, bag[i].value);
}
localStorage.remove(key);
};
return {
getItem: getItem,
exists: exists,
getValue: getValue,
putItem: putItem,
removeItem: removeItem,
count: count,
save: saveBag,
load: loadBag
};
};
module.factory('propertyBag', propertyBag);
})(angular.module('common'));
Here's the local storage code if you don't already have one (referenced in the code above)...
(function (module) {
var localStorage = function ($window) {
var store = $window.localStorage;
var add = function (key, value) {
value = angular.toJson(value);
store.setItem(key, value);
};
var get = function (key) {
var value = store.getItem(key);
if (value) {
value = angular.fromJson(value);
}
return value;
};
var remove = function (key) {
store.removeItem(key);
};
return {
add: add,
get: get,
remove: remove
}
};
module.factory('localStorage', localStorage);
})(angular.module('common'));

Resources