ng-repeat in angularJs avoid duplicate values - angularjs

I have object like this
{
{
"assetId" : "560",
"assetName" : "Testname",
"message" : "hai",
"timestamp" : 1452585984181
},
{
"message" : "haii",
"timestamp" : 1452585999592
},
{
"assetId" : "560",
"assetName" : "Testname",
"message" : "heloo",
"timestamp" : 1452586221604
}
}
show to this object i am using ng-repeat. My question is
I need to show all message using ng-repat comes under single assetName. but in this object two objects have same assetName and assetId. i need to show the messages both same objects but no need to repeatably show the assetName in top.
How can i only avoid the duplicate assetName and assetId. I used
<div class="container" data-ng-repeat="data in dataList | unique:'assetId'">
But it's completely removing the object. I need the message from all objects.
is it possible.Please help
This is the out put i am expecting.:

I think you should create your own custom filter
yourApp.filter('customuniqueFilter', function() {
return function( array, propertyThatMustBeUnique) {
var newArray = [];
for (i = 0; i++; i < array.length){
if ( notYetInYourArray ){ // I was too lazy to think about a way to do it ;-) feel free to update my answer
newArray.push(array[i]);
}
}
return newArray;
}
});
and then use it like this :
<div class="container" data-ng-repeat="data in dataList | customunique:'assetId'">

How about this:
<div class="container" data-ng-repeat="data in dataList | unique:'assetId'">
<span>{{data.assetId}}</span>
<div data-ng-repeat="data2 in dataList | filter:(data.assetId === undefined ? {assetId:'!'} : data.assetId)">
<span>{{data2.message}}</span>
</div>
</div>

Related

Can't make table in LWC

I want to make a table like this:
I got the values from the apex in js and it looks like this:
#track data2 = [];
#track data = [];
testClick() {
getExchangeRates({baseCurrency : this.defaultCurrency, dateFrom : this.dateFrom, dateTo : this.dateTo, value : this.defaultValue})
.then(resultJSON => {
let result = JSON.parse(resultJSON);
console.log(result);
console.log('////////');
console.log(result.rates);
let recordsByDates = result.rates;
for (var key in recordsByDates) {
console.log(key);
let record = {
date : key,
USD : recordsByDates[key].USD,
CAD : recordsByDates[key].CAD,
EUR : recordsByDates[key].EUR,
GBP : recordsByDates[key].GBP
}
this.data.push(record);
this.data2 = JSON.stringify(this.data);
}
console.log(this.data);
console.log(this.data2);
})
.catch(error => {
this.error = error;
console.log(error);
});
}
I tried to make a table, but something did not work out for me:
<template for:each={data2} for:item="dat">
<tr key={dat} onclick={testClick}>
<td data-label="data2">
{dat.key}
</td>
<td data-label="data2">
{dat.value}
</td>
</tr>
</template>
please tell me how to fix this
there are a couple of issues in the code:
not referring date value properly
should add a unique key, need in for:each
Here is the updated code
for (var key in recordsByDates) {
let record = {
key: key, // index of object can be used
date : recordsByDates[key].date,
USD : recordsByDates[key].USD,
CAD : recordsByDates[key].CAD,
EUR : recordsByDates[key].EUR,
GBP : recordsByDates[key].GBP
}
}
in HTML, you are referring wrong variable, it should data, in place of data2 (which is stringified).
no need to have table based tags for this type of structure, you can use div for better control.
in HTML file, it should be something like:
<template for:each={data} for:item="dat">
<div key={dat.key} onclick={testClick}>
<div class="date-wrap">
Date: {dat.date}
</div>
<div class="value-wrap">
USD: {dat.USD}
</div>
<div class="value-wrap">
CAD: {dat.CAD}
</div>
<div class="value-wrap">
EUR: {dat.EUR}
</div>
<div class="value-wrap">
GBP: {dat.GBP}
</div>
</div>
</template>
Moreover, you can create a nested array of objects inside the data variable which can help to make the structure more generic.

json arrays of object with quotaions mark

I am trying to send an json object to my apiController :
myJson Object that I construct dynamicaly like this :
var course= new Object();
course.info= $scope.info;
course.studentList = [];
course.studentList = $scope.results;
$scope.results is an array that I get from my view :
<select ng-model="results[$index]" >
<option value=""></option>
<option ng-repeat="r in myList" value={{r}}>{{r.studlastname}}</option>
</select>
what I expect :
{
"course": {
"courseName":"yyy",
"courseDesc":"xxxx",
"prof":"prof1"
},
"studentList" :[
{"studfirstname":"2","studlastname":"","studAge":"21"},
{"studfirstname":"4","studlastname":"","studAge":"40"},
{"studfirstname":"6","studlastname":"","studAge":"60"}
]
}
what I have :
{
"course": {
"courseName":"yyy",
"courseDesc":"xxxx",
"prof":"prof1"
},
"studentList" :[
"{"studfirstname":"2","studlastname":"","studAge":"21"}",
"{"studfirstname":"4","studlastname":"","studAge":"40"}",
"{"studfirstname":"6","studlastname":"","studAge":"60"}"
]
}
notice the quotations on every studentList element, this is causing deserialization problem on server side.
please can you help me to remove the quotations ?
thank you in advance.
From what I can see, Problem here is this
course.studentList = $scope.results;
because this line is adding string into your JSON Object as ng-model gives you string instead of object what you are adding in JSON Array.
course.studentList = JSON.parse($scope.results);
I found an easy solution :
let objectArray = $scope.results.map((each)=>{return JSON.parse(each)});
course.studentsList = objectArray;
this solved my problem.

unable to bind $scope.profile to a view from controller to view

theres what i've logged click on this link ok im now getting this objects with google data i want to dig in to username and id and be able to bind it. how do i do that?
d {$$conf: Object, $id: "google:107950469269631469408", $priority: null}
$$conf
:
Object
$id
:
"google:107950469269631469408"
$priority
:
null
-KK87pj5tW9EL8hL9To7
:
Object
id
:
"google:107950469269631469408"
name
:
"muzi ngobe"
__proto__
:
Object
How do i achieve this the fetching of object in objects?
var ref = new Firebase("https://tasksbylima.firebaseio.com/");
$scope.profile = $firebaseObject(ref.child('users').child(authData.uid));
console.log($scope.profile);
theres my firebase Json tree
{
"users" : {
"google:107950469269631469408" : {
"-KK87pj5tW9EL8hL9To7" : {
"id" : "google:107950469269631469408",
"name" : "muzi ngobe"
},
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="list card">
<div class="item item-divider">{{profile.name}}</div>
<div class="item item-body">
<form class="list">
<ion-checkbox>{{profile.name}}</ion-checkbox>
</form>
</div>
</div>
You can unwrap your answer object by accessing to the first property of object:
var ref = new Firebase("https://tasksbylima.firebaseio.com/");
var response = $firebaseObject(ref.child('users').child(authData.uid));
var users = response[Object.keys(response)[0]];
var google = users[Object.keys(users)[0]];
var key = google[Object.keys(google)[0]];
console.log(key);

ng-table filter with nested properties

I have following JSON:
[{
"Id": "1",
"Data": {"Str1": "Ann", "Str2": "Xenna"}
},{
"Id": "2",
"Data": {"Str1": "Bob","Str2": "Bobby"},
}]
And I created ng-table to display it. I tried to add filter. When I filter by Id everything works as expected (filter is { "Id": "2" }). But I cannot create proper filter do Str1 and Str2 fields. I already tried:
{ "Str1": "A" }
{ "Data.Str1": "A" }
{ "Data['Str1']": "A" }
but above options does not work.
Example of my work is here: http://plnkr.co/edit/MyJCqTlgvKLtSP63FYQY?p=preview
Update
Thanks to #Blackhole I founded that filter {Data: {Str1: 'A'}} works. But I can only delcare this in code. When I try to put something like this in HTML it doesn't even show filter:
<td data-title="'Str1'" filter="{Data:{Str1: 'text'}}">
{{ user.Data.Str1 }}
</td>
When you try to use filter="{Data:{Str1: 'text'}}" in html,input doesn't showing cause of template in header,have a look in source code.
<div ng-repeat="(name, filter) in column.filter"> //!!!! right here it's not supported
<div ng-if="column.filterTemplateURL" ng-show="column.filterTemplateURL">
<div ng-include="column.filterTemplateURL"></div>
</div>
<div ng-if="!column.filterTemplateURL" ng-show="!column.filterTemplateURL">
<div ng-include="'ng-table/filters/' + filter + '.html'"></div>
</div>
</div>
right here <div ng-repeat="(name, filter) in column.filter"> it's not dig into nested objects
Ngtable not support nested filter in default template,so you can create your own template,which gonna support it.Have a look to example of header template.
Note
This how column.filter is initializing,it's parsing from filter attribute on td tag,source
var parsedAttribute = function (attr, defaultValue) {
return function (scope) {
return $parse(el.attr('x-data-' + attr) ||
el.attr('data-' + attr) ||
el.attr(attr))
(scope, {
$columns: columns
}) || defaultValue;
};
};
var parsedTitle = parsedAttribute('title', ' '),
headerTemplateURL = parsedAttribute('header', false),
// here
filter = parsedAttribute('filter', false)(),
filterTemplateURL = false,
filterName = false;
...
columns.push({
....
filter: filter,

AngulaJS filter on array of object

I have this JSON object.
var UsersList=[
{
"User" : {
"IdUser" : "admin",
"FirstName" : "mirco",
"LastName" : "sabatino"
}
}, {
"User" : {
"IdUser" : "coordinator",
"FirstName" : "coordinator",
"LastName" : ""
}
}, {
"User" : {
"IdUser" : "test",
"FirstName" : "publisher",
"LastName" : "Diaz"
}
}, {
"User" : {
"IdUser" : "work",
"FirstName" : "ingester",
"LastName" : "Brown"
}
}
] ;
I want filter in ng-repeat for LastName value.
<div class="col-md-6" ng-repeat="users in UsersList | filter: {User.LastName : filterSearchLetter}">
filterSearchLetter value in my controler is populated by
$scope.filterLetterUser=function(letter){
$scope.filterSearchLetter=letter;
console.log($scope.filterSearchLetter);
};
But this don't work.
See my plnkr for the solution http://plnkr.co/edit/l27xUQ?p=preview. I also have implemented your required UI behavior using ng-change. Hope it helps.
For detailed explanation I offer you Todd Motto's blog - http://toddmotto.com/everything-about-custom-filters-in-angular-js/
To invoke a filter, the syntax is the filter function name followed by the parameters.
To define a filter you need to do (This is copy of Todd Motto's code modified for your data)
todos.filter('startsWithLetter', function () {
return function (items, letter) {
var filtered = [];
var letterMatch = new RegExp(letter, 'i');
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (letterMatch.test(item.User.LastName.substring(0, 1))) {
filtered.push(item);
}
}
return filtered;
};
});
This is not a valid object: {User.LastName : filterSearchLetter} It should actually throw an exception saying something like
Uncaught SyntaxError: Unexpected token .
What you probably want to try instead is: {"User": {"LastName" : filterSearchLetter} }
To iterate over an array of Objects see:
angularjs - ng-repeat: access key and value from JSON array object
You may have to convert to valid JS object using JS_Obj=JSON.parse(JSON_Obj);
Maybe something like this:
//iterate through array
<ul ng-repeat="users in UsersList">
//iterate through Object
<li ng-repeat=(key, value) in users | filter: {User.LastName : filterSearchLetter}>
{{key}} : {{value}}
</li>
</ul>

Resources