In my AngularJS project, I have developed a custom filter that categorizes elements by type and performs a search for multiple search terms across all attributes of devices.
angular.module('abc').filter('searchFor', function(){
return function(array, searchString){
var arr =[]
if(!searchString.length){
return array;
}
var result = [];
for(var i=0;i<array.length;i++){
//put all devices of all device Groups into arr
var temp = array[i].devices
for(var j=0;j<temp.length;j++){
arr.push(temp[j])
}
}
// search in tags of arr individual searchString
for(var i=0; i<searchString.length;i++){
searchString[i] = searchString[i].toLowerCase()
var res = []
for(var k in arr){
//there are some tags in device data object so I am searching in the same
var tags = arr[k].tags
tags.push(arr[k].ID)
tags.push(arr[k].Name)
tags.push(arr[k].Type)
for(var j in tags){
if(tags[j].toLowerCase().indexOf(searchString[i]) !== -1){
// if tags matches with searchString push it in res
res.push(arr[k]);
break;
}
}
result[i] = res
}
}
if (result.length > 1) {
result.sort(function(a,b) {
return a.length - b.length
})
for(i=0;i<result.length-1;i++){
var a = result[i]
var b = result[i+1]
var common = []
for (var j = 0; j < a.length; j++) {
for (var k = 0; k < b.length; k++) {
if (a[j].ID == b[k].ID) {
common.push(b[k])
break;
}
}
}
result[i+1] = common
}
resultFinal = common
}else {
resultFinal = result[0]
}
/* Finally resultFinal contains the devices satisfying the search
criteria
Before returning back group all the devices according to their
device types in deviceGroups(data Structure is as mentioned in demo
output) */
return deviceGroups
}
})
The purpose of this code snippet is to categorize an array of devices based on their 'type' parameter. Each device type has its own array of devices. However, there seems to be an issue causing an infinite digest loop.
Here are examples of input and output:
$scope.device_data = [
{name: 'D_1', type: 'wmeter'},
{name: 'D_2', type: 'fmeter'},
{name: 'D_3', type: 'smeter'},
{name: 'D_4', type: 'fmeter'}
]
The desired output should be organized like this:
[
'watermeter': [
{name: 'D_1'}
],
'flowmeter': [
{name: 'D_2'},
{name: 'D_8'}
],
'solar': [
{name: 'D_3'}
]
]
HTML snippet:
<div ng-repeat="group in deviceGroups | searchFor: searchString">
<h2>{{group.type.toUpperCase()}}</h2>
<div ng-repeat="device in group.devices">
<p>{{device.name}}</p>
</div>
</div>