cant print an object list in html - angularjs

Object {0: Object, 1: Object, 2: Object, 3: Object, 4: Object, httpStatus: 200, httpStatusText: null, httpBodyText: "[object Object],[object Object],[object Object],[object Object],[object Object]"}
0:Object (example of object i opened to show content)
CountryInitials : "US"
Id: "101"
CountryName: "United States"
Population: 318.9
__proto__:
Object
1:Object
2:Object
3:Object
4:Object
this is an example from my browser that shows how im receiving the data, so its a object that contains objects, and I want to treat it in the html like its an array, and i thought it is but its not working....
this is the html:
<div *ngFor="#obj of myList>
<div><b>Country ID:</b> {{obj.Id}} <b>Country Name:</b> {{obj. CountryName}}}</div>
</div>
and its not working...I dont know why, i just want to present a list of the objects with country id and country name..
the EXCEPTION:
EXCEPTION: Error trying to diff '[object Object]' in [myList in EntityBulkCmp#32:31]
could someone please help me figure this out?
thanks!

You can use the pipe json to print an object inside the template: https://angular.io/docs/ts/latest/api/common/index/JsonPipe-pipe.html
#Component({
selector: 'json-pipe',
template: `<div>
<p>Without JSON pipe:</p>
<pre>{{object}}</pre>
<p>With JSON pipe:</p>
<pre>{{object | json}}</pre>
</div>`
})
export class JsonPipeComponent {
object: Object = {foo: 'bar', baz: 'qux', nested: {xyz: 3, numbers: [1, 2, 3, 4, 5]}};
}

The Exception says items in myList are not unique. Probably you have some repeated elements.
Angular needs to keep track of which item it is enumerating.
Use trackBy option, find the syntax below
<li *ngFor="let item of items; let i = index; trackBy: trackByFn">...</li>
refer https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html for complete usage of the directive.

you can use key and value to print the json format...
In which key is 0, 1, etc (as in your case) and value is object (as in your case)...

Related

Cannot find a differ supporting object '[object Object]' of type 'object'. - context menu issues

I have issues with context menu. I am not sure why, I made similar thing many times but now I am unable to pass it. When I deleted this line:
<div *ngFor="let element of contextMenu">
</div>
Context menu works fine (but I need this line to fill my context menu.
This is part of html:
<mat-menu #contextMenu="matMenu">
<ng-template matMenuContent>
<div *ngFor="let element of contextMenu">
</div>
</ng-template>
</mat-menu>
And my context menu object:
#Input() contextMenu: MenuElement[];
And html with filled input:
<lib-mp-file-explorer
[fileElements]="fileElements | async"
[path]="currentPath"
[canNavigateUp]="canNavigateUp"
[topMenu]="topMenu"
[contextMenu]="contextMenu"
(folderAdded)="addFolder($event)"
(elementRemoved)="removeElement($event)"
(navigatedDown)="navigateToFolder($event)"
(navigatedUp)="navigateUp()"
(elementRenamed)="renameElement($event)"
(elementMoved)="moveElement($event)"
>
</lib-mp-file-explorer>
And my construction:
this.contextMenu = [
{
name: 'Open in Mark',
icon: 'M',
action: undefined,
disabled: true
},
...
]
I hate this error now:
core.js:5828 ERROR Error: Cannot find a differ supporting object
'[object Object]' of type 'object'. NgFor only supports binding to
Iterables such as Arrays.
But my array is iterable T.T
Your menu reference variable has the same name..
<mat-menu #contextMenu="matMenu">
..as the array you are trying to loop through
<div *ngFor="let element of contextMenu">
A template reference variable is not iterable.
Try renaming your array:
<div *ngFor="let element of menuElements">
And Input():
#Input() menuElements: MenuElement[];
and then
this.menuElements = [
// your data
]
You can check what there are actual values in your contextMenu:
<p>contextMenu {{ contextMenu | json }}
However, your error says that it is object, so you can use keyvalue pipe since Angular 6:
<div *ngFor="let item of contextMenu | keyvalue">
Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
</div>

extracting information from array using knockout

I currently have an array being passed into my function and i wanted to pull out the information from the array so i can display it on the page.
This is what the array looks like:
EducationalClasses:[object, object]
first object contains:
classId: "324342",
className: "English 101"
second object contains:
classId: "231243",
className: "Reading"
when i do educationalClasses[0] i get the results as in first object. I wanted to create some sort of loop so that in my view page when i have:
<!-- ko foreach: educationalClasses -->
<div data-bind="text: className></div>
<!--/ko-->
i would get English 101 and Reading displayed
This is what i have for my viewModel:
viewModel = function(educationalClasses){
....
self.className= ko.observable(educationalClasses.className); // what i want
}
How can i do this properly and so that all the items in the array are displayed without me having to use educationalClasses[0].className...educationalClasses[1].className
Technically, you don't need any observables for what you're doing here. You just need your viewmodel to have a member named educationalClasses that is an array (or observableArray). You can just wrap your raw data in an object, label it, and it goes.
If you want to change the array and have the view show the updates, you'll want an observableArray. If you want changes to the individual data items to show, you'd want them to be observables as well.
rawData = [{
classId: "324342",
className: "English 101"
}, {
classId: "231243",
className: "Reading"
}];
viewModel = function(educationalClasses) {
return {
educationalClasses: educationalClasses
};
};
ko.applyBindings(viewModel(rawData));
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<!-- ko foreach: educationalClasses -->
<div data-bind="text: className"></div>
<!--/ko-->

angularJS - How to filter by one item in object only

In this JSFiddle (https://jsfiddle.net/eug0taf9/9/), I select a rating and expect an image to be displayed.
What is happening?
When I select rating 'High', 2 images show up instead of 1 because the filter is catching category 'High' and also description 'High' of an image in category 'Low'.
What do I expect to happen?
On selecting rating "High", I only want the category to be filtered. I don't need it to be filtered by description too.
Any suggestions on how to solve this?
HTML code:
<div ng-app="myApp" ng-controller="myCtrl">
<span>Select a rating</span>
<select ng-model="catselect"
ng-options="category for category in imageCategories"
ng-change="valueSelected(catselect)">
<option value>All</option>
</select>
<!--<p>Select <input ng-model="categories"/></p>-->
<ul class="photosmenu">
<li ng-repeat="image in images | filter : catselect" ng-click="setCurrentImage(image)">
<img ng-src="{{image.image}}" alt="{{image.stars}}" width="300px"/>
</li>
</ul><!-- End of List -->
</div>
Angular Code:
var mod = angular.module("myApp", []);
mod.controller("myCtrl", function($scope){
$scope.images = [
{category: 'High', image: 'img/1.png', description: 'Random Photo', stars: '4/5'},
{category: 'Medium', image: 'img/6.png', description: 'ApplePhoto', stars: '3/5'},
{category: 'Low', image: 'img/13.png', description: 'High Top Photo', stars: '2/5'},
{category: 'None', image: 'img/16.png', description: 'Kilt Photo', stars: '0/5'}];
$scope.currentImage = $scope.images[0];
$scope.imageCategories = ["High", "Medium", "Low", "None"];
$scope.valueSelected = function (value) {
if (value === null) {
$scope.catselect = undefined;
}
};
});
That is because you have a global match filter which will match on all properties, if you want to filter on specific property set your filter object accordingly. i.e
<li ng-repeat="image in images | filter :{category: catselect}"
Demo
or you could also set your ng-model to an object,
<select ng-model="catselect.category"
and do:
<li ng-repeat="image in images | filter :catselect"
Demo
Check out documentation:
string: The string is used for matching against the contents of the array. All strings or objects with string properties in array that match this string will be returned. This also applies to nested object properties. The predicate can be negated by prefixing the string with !.
Object: A pattern object can be used to filter specific properties on objects contained by array. For example {name:"M", phone:"1"} predicate will return an array of items which have property name containing "M" and property phone containing "1". A special property name $ can be used (as in {$:"text"}) to accept a match against any property of the object or its nested object properties. That's equivalent to the simple substring match with a string as described above. The predicate can be negated by prefixing the string with !. For example {name: "!M"} predicate will return an array of items which have property name not containing "M".

jquery template array inside of array

I've a json object like this
[Object]
0: Object
domains: Array[1]
0: "domain1.com"
length: 1
__proto__: Array[0]
name: "name1"
1: Object
domains: Array[2]
0: "domain2.com"
length: 1
__proto__: Array[0]
name: "name2"
These objects are generated on the client and I want to display them by using jQuery.tmpl plugin. I've defined a template to be:
<script id="domain_template" type="text/x-jquery-tmpl">
{{each response}}
{{each response.domains}}
<div class="dummy_copy" data-srvType="${srvType}" data-domain="${domain}">"${value}"</div>
{{/each}}
{{/each}}
</script>
What did i do wrong with it here? thanks
You're code should be:
{{each response}}
{{each $value.domains}}
or
{{each response}}
{{each domains}}
and if you wont to have values: srvType, domain, value they must be members of objects that you store in domains
First of all, i convert to JSON my object like this.
arr = []
for srv in response
for domain in srv.domains
arr.push srvType: srv.srvType, domain: domain
domainTmpl = $.tmpl $(#domainTemplate).template(), arr
After having json object it was rendered by jquery template.This will helpfull for all i think

get not retrieving name attribute from object

From the backbone docs
getmodel.get(attribute)
Get the current value of an attribute from the model. For example: note.get("title")
I seeded some data with a name for each country into a Rails app
Country.create!(name: "Brazil")
Country.create!(name: "France")
Country.create!(name: "Germany")
Country.create!(name: "Spain")
In the console, I created a new collection and fetched the data
countries.fetch();
Object
XHR finished loading: "http://localhost:3000/countries".
Checked the length. Equal to the four countries I created.
countries.length
4
Selected a random one using underscore's shuffle method.
c = countries.shuffle()[0]
The object has a name
Backbone.Model
_changes: Array[2]
_currentAttributes: Object
_events: Object
_hasComputed: false
_previousAttributes: Object
attributes: Object
country: Object
created_at: "2013-01-07T06:09:43Z"
id: 2
name: "France"
updated_at: "2013-01-07T06:09:43Z"
__proto__: Object
__proto__: Object
Tried to get the name attribute from the object several different ways, all without success
c.get('name')
undefined
c.get("name");
undefined
c.get("name")
undefined
Can anyone think what I might be doing wrong?
One thing that I find unusual is that there is a 'country' attribute wrapping the other attributes
attributes: Object
country: Object
created_at: "2013-01-07T06:09:43Z"
id: 2
name: "France"
updated_at: "2013-01-07T06:09:43Z"
I'm not sure why 'country' is wrapping the other data. Is it because I created the seed data with a Country model?
Country.create!(name: "Brazil")
anyways, obj.get('country') doesn't return undefined
c = countries.shuffle()[0]
k = c.get('country')
Object
created_at: "2013-01-07T06:09:43Z"
id: 3
name: "Germany"
updated_at: "2013-01-07T06:09:43Z"
__proto__: Object
but I can't do a get on the name after that (i.e after I did the get on country)
k = c.get('country')
Object
k.get('name')
undefined
Is there a way to remove the country wrapper and just be able to do get on the attributes that it was created with?
Override model.parse to extract the country element. Backbone calls parse before populating the model from fetched data:
var Country = Backbone.Model.extend({
parse: function(attributes) {
return attributes.country;
}
});

Resources