I have two json objects (data1 and data2) that have related information. Namely, both objects have properties (arrays) which in turn can have identical data. So, I am trying to figure out how to display those data with highlighting them properly, i.e. identical data with green color and non-identical with red color. Somehow it wrongly highlights all data with red color.
Here is the html:
<ul>
<li ng-repeat="item in vm.data2.features"
ng-class="vm.data1.features.indexOf(item) !== -1 ? 'check' : 'uncheck'">
<span ng-bind="item.id"></span>
</li>
</ul>
and objects:
vm.data1 = {
id: '4569',
name: 'Given data',
features: [
{id: "TEST_TEXT2", desc: 'smth12'},
{id: "TEST_PPP", desc: 'smthsmthsmth'},
{id: "TEST_ECASH", desc: "somelongtexthere"}
]
};
vm.data2 = {
id: '1305',
name: 'Base data',
features: [
{id: "TEST_BP", desc: 'smth'},
{id: "TEST_TEXT2", desc: 'smth12'},
{id: "TEST_PPP", desc: 'smthsmthsmth'},
{id: "TEST_TEXT1", desc: 'blahblah'},
{id: "TEST_ECASH", desc: "somelongtexthere"}
]
};
The full demo is here.
Any help would be appreciated.
Indexof() method will look for similarity in object references not the id itself. findIndex() method can help you here instead.
vm.hasFeature = function(item){
var hasElements= vm.data1.features.findIndex(function(e){
return e.id == item.id;
});
console.log(item, hasElements);
return hasElements;
}
And in html
<li ng-repeat="item in vm.data2.features"
ng-class="vm.hasFeature(item) > -1 ? 'check' : 'uncheck'">
vm.hasFeature = function(item){
var hasElements= vm.data1.features.findIndex(function(e){
return e.id == item.id;
});
console.log(item, hasElements);
return hasElements;
}
CodePen Link: https://codepen.io/anon/pen/ewgLBN?editors=1010
None of the objects will be the same because indexOf(item) will compare object references of item. You'll need to do a deep equals comparison of the items.
i.e.
{id: "TEST_TEXT2", desc: 'smth12'} === {id: "TEST_TEXT2", desc: 'smth12'} // false
vm.data1.features[0] === vm.data1.features[1] // false
Example using lodash would be something like:
_.some(vm.data1.features, otherItem => _.isEqual(item, otherItem))
Because
_.isEqual(vm.data1.features[0], vm.data2.features[1]) // true
Docs for Lodash:
_.some
_.isEqual
Related
I want to know how to get value in array in *ngFor. First I use *ngFof to get item list. Second I use commonService.indexKey$.getValue() to check id in commonService.quantityList$.getValue() available or not
This is my code
HTML
<div *ngFor="let item of commonService.quantityList$.getValue(); let i = index" class="Box">
<label>Qty : {{commonService.indexKey$.getValue()== item.id?item.quantity - commonService.indexKey$.getValue().count:item.quantity}}</label>
</div>
Example data
commonService.quantityList$.getValue()
quantity = [
{ id:1, quantity:100 },
{ id:2, quantity:200 },
{ id:3, quantity:30 }
];
commonService.indexKey$.getValue()
indexCount = [
{id: 1,count: 2},
{id: 2,count: 3},
{id: 3,count: 4},
]
Not sure what are you trying to do in your label really because seems you are making a comparison “==“ so the label will output “true” or “false”. Is that what you really want?
<div *ngFor="let item of commonService.quantityList$.getValue(); let i = index" class="Box">
<label>Qty : {{commonService.indexKey$.getValue()[i]== item.id?item.quantity - commonService.indexKey$.getValue()[i].count :item.quantity}}</label>
</div>
I want to filter the values of a <select>.
I have a table with first column <select> .
For eg: object for the <select> is
JSON:
json1 = [{id: 1, name: 'ABC'}, {id: 2, name: 'DEF'}, {id: 3, name: 'XYZ'}, {id: 4, name: 'ASD'}, {id: 5, name: 'QWE'}]
json2 = [{id: 1, name: 'ABC'}, {id: 2, name: 'DEF'}]
My requirement is: We need to show values from json1 in ng-options but which object should not be there in json2.
For eg: First 2 rows will be filled with json2. So we need to provide options 'XYZ' 'ASD' and 'QWE' in the following rows.
Suppose if name 'XYZ' is selected in the dropdown of the third row. then 4th row <select> should show only 'ASD', and 'QWE'. Similarly what ever object selected in other rows shouldn't be shown in option of other rows dropdown.
I have tried something like this
<select ng-model="obj"
ng-options="obj.id as obj.name for obj in json1 | myFilter:json2">
</select>
myApp.filter('myFilter', function(json2) {
return function(json1) {
var filtered = [];
json1.forEach((d) => {
var exists = false;
json2.forEach((ad) => {
if(ad.id == d.id) {
exists = true;
}
});
if(!exists) filtered.push(d);
});
console.log(filetered);
return filtered.length > 0 ? filtered : json1;
};
});
In filter console.log() values are filtered correctly as expected. However in ng-options all options from json1 are still available not updated with filtered values.
What's wrong?
Is this what you are looking for?
For example:
<table>
<thead>
<tr>
<th>Unique</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="product in products">
<td>
<select ng-model="product.unique" ng-options="obj.id as obj.name for obj in (json1 | myfilter:products:$index)">
<option value="">No select</option>
</select>
</td>
<td ng-bind="product.name"></td>
</tr>
</tbody>
</table>
vm.products = [{name: 'Product 1'}, {name: 'Product 2'}, {name: 'Product 3'}, {name: 'Product 4'}, {name: 'Product 5'}];
vm.json1 = [{id: 1, name: 'ABC'}, {id: 2, name: 'DEF'}, {id: 3, name: 'XYZ'}, {id: 4, name: 'ASD'}, {id: 5, name: 'QWE'}];
App.filter('myfilter' , [function() {
return function(json1, products, index) {
// Filter all products, except the mime
productsFilter = products.filter(function(product, i) {
return i !== index;
});
// filter those that have not yet been selected
var json1Filter = json1.filter(function(item) {
// ask if there is the id in a product
return !productsFilter.some(function(product) {
return item.id == product.unique;
});
});
return json1Filter;
};
}]);
Example Codepen: https://codepen.io/anon/pen/vMJyLz
I think you have the parameters to your filter slightly wrong. The filter function takes a first parameter as the value to be filtered and the other parameters are the ones after myFilter:.
I'm not 100% sure what you want to happen here, but your filter function is called for each value in the dropdown list and should return a replacement for the given value.
However, your code is returning an array of items. This is not how a filter works in AngularJS.
Your filter needs to be updated to check if the item being passed into the filter should be shown or not, and if not, return false.
You can look at the script example from the AngularJS docs to see how they show to do this, or this other Stack Overflow question/answer.
I've got an application where I retreive the information of some objects (into an array). That array would have the following structure:
$scope.items = [
{
id: 23289323,
event: {
id: 972823,
name: 'Event A name',
datetime: '2017-02-01 13:45',
},
player: {
id: 58392,
name: 'Player A name'
},
team: {
id: 38839,
name: 'Team A'
},
datetime: '2017-02-03 22:23'
},
{
id: 482273784,
event: {
id: 972823,
name: 'Event A name',
datetime: '2017-02-01 13:45',
},
player: {
id: 2989273,
name: 'Player B name'
},
team: {
id: 2323434,
name: 'Team B'
},
datetime: '2017-02-03 22:23'
},
{
id: 283273939,
event: {
id: 23092803,
name: 'Event B name',
datetime: '2017-02-01 13:45',
},
player: {
id: 58392,
name: 'Player A name'
},
team: {
id: 38839,
name: 'Team A'
},
datetime: '2017-02-03 22:23'
}
...
]
What I'd like
I'd like to be able to have two lists.
On the left, a list of some customizable groupingBy AngularJS filter. So, I can specify "group it by player" and it shows, on this left list, a list of the players with some information (for example, showing the player's name).
On the right, when I select a specific player, show the items that have this player associated.
What I've tried
<li data-ng-repeat="(key, value) in Ctrl.items | groupBy: 'event.id'">
{{key}}<br/>{{value}}
</li>
What I get
23289323
{id: 23289323,event: {id: 972823,name: 'Event name',datetime: '2017-02-01 13:45',}, player: {id: 58392, name: 'Player name'}, team: { id: 38839,name: 'Team A'}, datetime: '2017-02-03 22:23'}
So, I'm getting the whole item object, but I've not found any way of getting the item that I'm groupBying. Because, right now, if there are 3 items with that event.id I get three <li></li> in stead of only one (the one of the event object).
What I ask
Is there any way of using AngularJS groupBy filter and getting in return the (whole) object that is specifying the grouping?
Remember that the groupBy key can be changed by the user.
If you need any further information, please let me know.
Thank you!
I think I've made it through a custom filter. I'm not sure if it's the best way, so if anyone has another solution, please post it!
This is the code of the filter:
(function(){
angular.module("AppModule").filter('groupByGrouped', function() {
return function(list, groupedElement) {
var result = [];
var used_elements = [];
var ref_item;
var ref_check;
// Loop through every list item
angular.forEach(list, function(item){
// We take the object we want to group by inside the item
ref_item = item[groupedElement];
// If it exists
if(ref_item !== undefined){
if(ref_item.id !== undefined){
// If it has an ID, we take the ID to make it faster.
ref_check = ref_item.id;
}else{
// Otherwise, we identify the specific object by JSON string (slower method)
ref_check = JSON.stringify(ref_item);
}
// If it does not exist yet
if(used_elements.indexOf(ref_check) == -1){
// We add it to the results
result.push(ref_item);
// And we add it to the already used elements so we don't add it twice
used_elements.push(ref_check);
}
}else{
// Otherwise we log it into our console
console.warn("The key '"+groupedElement+"' inside the specified item in this list, does not exist.");
}
});
return result;
};
});
})();
This will return the whole object. So our HTML would be something like:
<ul>
<li data-ng-repeat="(key, obj) in Ctrl.items | groupByGrouped: 'event'">
<span class="object_id">{{obj.id}}</span>
</li>
</ul>
Or even with a directive (not tested, but should work aswell):
<ul>
<li data-ng-repeat="(key, obj) in Ctrl.items | groupByGrouped: 'event'">
<obj_directive ourobject="obj"></obj_directive>
</li>
</ul>
What is the reason behind this code working
return state.update(action.id, function(item) {
return {id: item.id, title: item.title, duration: item.duration - 1 };
});
and this one that does not work?
return state.update(action.id, function(item) {
item.duration = item.duration - 1;
return item;
});
What is the main difference?
ImmitableJS's List is not "deeply immutable". item is a reference. For you to end up with a new List reference after this operation (and your React components to know something changed) the List references themselves need to change, not just data inside the objects referenced by items.
The reason your first example works is that you are dropping a reference from the List and adding a new one, meaning you get a new List (different reference).
The second example does not alter the references themselves, just the data in the objects, thus you won't get a new List reference.
You could initialize this List by doing a Immutable.fromJS() to get your initial List instance. This one is going to create a "deeply immutable" List that will behave like you expect it to in your second example.
Try this (here's the fiddle for it):
var list = Immutable.List([ {id: 1}, {id: 2}, {id: 3} ]);
var deepList = Immutable.fromJS([ {id: 1}, {id: 2}, {id: 3} ]);
var mutatedList1 = list.update(0, function(item) {
item.id = 'x';
return item;
});
var mutatedList2 = list.update(0, function(item) {
return {id: 'x' };
});
var mutatedList3 = deepList.update(0, function(item) {
return {id: 'x' };
});
console.log(list.get(0), mutatedList1.get(0), list.get(0) === mutatedList1.get(0), list === mutatedList1);
console.log(list.get(0), mutatedList2.get(0), list === mutatedList2);
console.log(deepList === mutatedList3);
With this output:
Object {id: "x"} Object {id: "x"} true true
Object {id: "x"} Object {id: "x"} false
false
For React to know your list changed the comparison has to be false.
I am posting this because I never found a precise answer for filtering nested objects (tree sturcture).
Let's say we have an JSON tree structure that looks like this:
$scope.tree = [{
id: 1,
parent_id: 0,
name: 'Root Item',
items: [
{
id: 2,
parent_id: 1,
name: '1st Child of 1'
},
{
id: 3,
parent_id: 1,
name: '2nd Child of 1'
},
{
id: 4,
parent_id: 1,
name: '3rd Child of 1',
items:[
{
id:5,
parent_id: 4,
name:'1st Child of 5'
},
{
id:6,
parent_id: 4,
name:'2nd Child of 5'
}
]}
]
}]
How do we traverse the tree with a filter to get object with id 6 for example?
If we use the following filter for example:
<div data-ng-init="selectedItem = (tree | filter:{id:6})">
<h1>The name of item with id:6 is selectedItem.name</h1>
</div>
It will only iterate through the first level in which will only find id:1.
So, in order to get nested level objects we must use a recursive filter like this one:
angular.module("myApp",[])
.filter("filterTree",function(){
return function(items,id){
var filtered = [];
var recursiveFilter = function(items,id){
angular.forEach(items,function(item){
if(item.id === id){
filtered.push(item);
}
if(angular.isArray(item.items) && item.items.length > 0){
recursiveFilter(item.items,id);
}
});
};
recursiveFilter(items,id);
return filtered;
};
});
});
So, to use this filter in the markup you would call it like this:
<div data-ng-init="selectedItem = (tree | filterTree:6)">
<h1>The name of item with id:6 is selectedItem.name</h1>
</div>
Hope you find this useful, it took me some time to digest recursive filters.
Of course, this filter works to get 1 item since it returns [0] first object of filtered array. But if you want it to return more than 1 result you'll have to remove only that [0] at the return function and then use ng-repeat to iterate over filtered resutls.