I'm very new to AngularJS. This is my first foray into any sort of JS, so I apologize if I've butchered anything.
Here's a brief overview of what I'm trying to do.
The user inputs a term to search, and I get the information from Twitter. The tweets are displayed with an ng-repeat (making my issue MORE frustrating). The user checks which tweets he/she would like to add to a "cart". Ipush tweets which are selected onto my service's array ("shoppingCart" inside the cart service).
I then click "Add to cart" to transfer to a new page (results.html) where I would like to display what the user selected.
Note: For our purposes here, I've skipped this and hardcoded the results.
This is where it all breaks down. I can console print the array to make sure the service is received by the next controller, but I can't get ng-repeat to work.
I have absolutely no clue what I've messed up here. I'm still very new to Angular so it's likely I've made a dumb mistake. I've tried to read through a docs and have checked out egghead.io videos. Unfortunately I just can't put two and two together.
Here is the service with the array hardcoded:
myApp.service('cart', function Cart($rootScope) {
var self = this;
var shoppingCart = [{
"created_at": "Wed, 17 Apr 2013 17:52:42 +0000",
"from_user": "LopezCarlosB",
"from_user_id": 244705286,
"from_user_id_str": "244705286",
"from_user_name": "carlos lopez",
"geo": null,
"id": 324581196224938000,
"id_str": "324581196224937984",
"iso_language_code": "en",
"metadata": {
"result_type": "recent"
},
"source": "",
"text": "#Medicencaballo #ponnyloca AHHH AHH LESLEEEEEY ASD SIGYGIS",
"to_user": "Medicencaballo",
"to_user_id": 202598647,
"to_user_id_str": "202598647",
"to_user_name": "Axel Manrique",
"in_reply_to_status_id": 324580938027765760,
"in_reply_to_status_id_str": "324580938027765760"
}, {
"created_at": "Wed, 17 Apr 2013 17:52:35 +0000",
"from_user": "WhatNowTweeting",
"from_user_id": 383266399,
"from_user_id_str": "383266399",
"from_user_name": "Herman",
"geo": null,
"id": 324581166764130300,
"id_str": "324581166764130305",
"iso_language_code": "en",
"metadata": {
"result_type": "recent"
},
"source": "",
"text": "Life on the spectrum: 5 books about autism and Asperger's - Mother Nature Network #autism #asperger #pddnos #pdd #asd"
}, {
"created_at": "Wed, 17 Apr 2013 17:52:32 +0000",
"from_user": "Elchinitooooo",
"from_user_id": 903231720,
"from_user_id_str": "903231720",
"from_user_name": "ChinoCochino..^^",
"geo": null,
"id": 324581154667782140,
"id_str": "324581154667782147",
"iso_language_code": "es",
"metadata": {
"result_type": "recent"
},
"source": "",
"text": "Mañana viene mi amor :3 asd asd"
}];
self.add = function (item) {
shoppingCart.push(item);
}
self.count = function () {
console.log(shoppingCart);
return shoppingCart.length;
}
self.log = function () {
return shoppingCart;
}
});
Here is the controller for the view below:
myApp.controller('ResultsCtrl',
function ResultsCtrl($scope, $resource, cart) {
$scope.cart = cart;
$scope.shoppingCart = cart.shoppingCart;
});
Here is the html for that view:
<div>
<table>{{cart.log()}}
<br>
<ul>
<li ng-repeat="item in shoppingCart">{{item.text}}</li>
</ul>
</table>
</div>
I'm not getting any errors in Firebug, so I'm imagining I'm not referencing the array correctly, but have been unable to figure out how.
Thank you very much for any assistance you might be able to offer.
It looks like you're trying to accessing the shoppingCart var directly from your controller with the line
$scope.shoppingCart = cart.shoppingCart;
However, shoppingCart isn't attached to self/this, effectively making it private, so I don't think that type of access is possible. The log method in your service returns the shoppingCart var, so maybe it'll help if you change that above line to:
$scope.shoppingCart = cart.log();
I'm not exactly sure if that will work using the .service method, so if it fails you may want to look into using .factory instead, which does basically the same as .service but allows you to return an object that will be the service rather than this.
Related
I am new to Ionic 3 & Angular and ran into an issue with *ngFor and .subscribe() method. Please forgive me if it is an easy question. I tried to figure out the behaviour of http.get(..).map(..).subscribe() function when used along with *ngFor to maintain an array of objects and show the records to user using *ngFor on the .html template file but unable to know *ngFor's odd behaviour.
In my Ionic 3 App, I am getting the data using an API and storing it inside a component variable called "users" which is declared as below in component .ts file -
users: Array<any>;
I have below component function which gives me data for this users array -
addUser(count: number) {
this.http.get('https://randomuser.me/api/?results=' + count)
.map(data => data.json().results)
.subscribe(result => {
for (let val of result) {
this.users.push(val);
}
})
}
Initially, I get data for 10 users from the API using above component function by simply calling it inside my ngAfterViewInit() function like -
this.addUser(10);
This gives me 10 user record objects inside my users array which I show to the user using something like below in the view .html file -
<ion-card *ngFor="let user of users">
{{user.email}}
</ion-card>
At this time *ngFor puts the last array element at first in the view and shows the records in the descending order as the elements in the array starting from index 9 to 0.(LIFO order)
Now I start popping the last element from this users array using users.pop(); and push another element at the beginning at index 0 by shifting current elements using users.unshift(..) in below function and calling it as addNewUser(1); -
addNewUser(count: number) {
this.http.get('https://randomuser.me/api/?results=' + count)
.map(data => data.json().results)
.subscribe(result => {
for (let val of result) {
this.users.unshift(val);
}
})
}
At this moment, if we consider the first array which had 10 elements, the last object at index 9 had been removed and another element at index 0 has been added making the previous elements on index 0-8 to shift to index 1-9.
On doing so, my view gets updated which has *ngFor and surprisingly this time it shows the first element at first place which is actually on index 0 which is the one I recently put. This is opposite to the order earlier followed by *ngFor to render elements on the screen.
Why *ngFor in Ionic 3 view shows the recently inserted object element first from the array of objects which is dependent on the subscribe method .subscribe() method. I am really confused about this.
I really need to clear the concept of *ngFor and subscribe(). Please help me.
Note : The API mentioned above is publicly accessible for testing and you may call it to check the response structure if required.
Pasting a sample API response below on calling https://randomuser.me/api/?results=1 -
{
"results": [
{
"gender": "male",
"name": {
"title": "mr",
"first": "daniel",
"last": "stoll"
},
"location": {
"street": "9719 tannenweg",
"city": "cottbus/chosebuz",
"state": "bremen",
"postcode": 81443
},
"email": "daniel.stoll#example.com",
"login": {
"username": "greenleopard994",
"password": "chat",
"salt": "OUjisBdQ",
"md5": "8148d51998f3fef835a5f3979218c181",
"sha1": "131ae09d045b345efe36a330bf17a450b76f7de3",
"sha256": "94c3a362b5f516d0fb1d4e9dbb632d32d57b8886d5cc7bf0d5cedc99e7d55219"
},
"dob": "1957-04-26 22:07:14",
"registered": "2002-04-29 10:57:34",
"phone": "0556-4348870",
"cell": "0172-5116200",
"id": {
"name": "",
"value": null
},
"picture": {
"large": "https://randomuser.me/api/portraits/men/14.jpg",
"medium": "https://randomuser.me/api/portraits/med/men/14.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/men/14.jpg"
},
"nat": "DE"
}
],
"info": {
"seed": "8fd4afe85884c767",
"results": 1,
"page": 1,
"version": "1.1"
}
}
Refer this example showing my issue.
If you have a sorting issue with indexing and you think it's related.. you could work around the issue by assigning an index:
*ngFor="let user of users; let i = index"
and then reference the direct index value
users[i]
You should make a copy of that array. Editing array elements while looping them can lead to unexpected behaviour.
I guess I'm stuck on stupid. I've been at this for the last few hours and can't seen to figure it out. Admittedly, I am new to ng/ionic2.
I am trying to loop through the response from my post request. I am getting a valid(validated online) big, fat JSON object from my own web api. It looks like this:
`"details": [{
"item_ID": "4",
"item_attribute_ID": "JiggyJamband_1_642",
"item_color_bool": "false",
"item_name": "Test Item 4",
"item_price": "18.95",
"item_desc": "4 This is a test of the ajax input",
"item_gender": "Girls"
},
{ ... },
"attributes": {
"JiggyJamband_1_642": [{
"color": "no-color",
"Xs": "80",
"Sm": "0",
"Med": "0",
"Lrg": "0",
"Xl": "0",
"Xxl": "10"
}],
"JiggyJamband_5_5664": [{
"color": "no-color",
"Xs": "0",
"Sm": "0",
"Med": "0",
"Lrg": "0",
"Xl": "0",
"Xxl": "50"
}],
{ ... }`
I am able to access individual "details" and "attributes" like this:
this.itemsDataService.getRemoteData(urlCode)
.subscribe(response => {
this.itemsJson = response;
this.dObj = this.boothItemsJson.details;
//this.aObj = this.boothItemsJson.attributes;
this.aObj = response["attributes"]["JiggyJamband_1_642"];
});
My provider looks like this:
getRemoteData(urlCode): any {
return this.http.post('http://localhost/process-fe-app/_itemJson.php', JSON.stringify(urlCode))
.map(res => res.json()); }
My question: items in details is dynamic and has an item-attribute_ID that is related to at least 1 entry in attributes. Entrys for attributes are dynamic as well - each item can have multiple attributes. The array keys of the individual attributes are the static (sizes and colors) and either have values or they don't. I need to be able to loop over the attributes object (aObj) of arrays and the arrays inside them. I do not need the ngFor or ngIf statements as this data won't be directly displayed per se. The json data is returned just fine but I just need to be able to access it call methods on the based on the data (like putting into storage with the attribute ID as the key "JiggyJamband: color: no-color, xs:50, s:100... etc"
What I've tried: this tutorial https://www.youtube.com/watch?v=0kHJgw6Li_4, and googling ever iteration of the wording for this problem I could think of.
Perhaps this sample iteration will help you get your head around it.
this.itemsDataService.getRemoteData(urlCode)
.subscribe(response => {
for(var k in response){
for(var k2 in response[k]){
console.log([k,k2,response[k][k2]]);
}
}
});
I have built an app for a client using my basic / beginner knowledge of Angular. It took me a lot longer than most would but it has been a great learning experience for me.
The app imports JSON data which displays products with each returned result linking to a page with more information.
The products are manually filtered i.e. I Have built pages for all possible filters (the long hard way). This is displayed as 4 initial options then you go to another page with another 4 options based off the previous option then a final page with 4 further options from here a list is returned based on the the previous selections. This way has led to a large collection of JSON files all based off the filter combinations available.
Background story aside my client now wants to be able to filter all data using drop downs on the opening page. Is this possible?
My JSON data looks like below as an example
{"Level":"student","Style":"barb","Handle":"left","ItemCode":"5.25: 606603, 5.75: 606607","title":"Jaguar Prestyle Relax Leftie","Size":"5.25, 5.75","Price":"£50.00","Description":"One micro-serrated to prevent hair bunching or slippage, these are a particularly good choice for barbers. These scissors are ergonomically designed to reduce strain on your hands and wrists, with an offset handle, finger rest and finger ring inserts for extra comfort. Made from stainless steel with a matt satin finish.","picture":"img/stubarbleft/1.jpg"}
What I would like to do is display the returned data which is not an issue I can do that part. At the top of the page I would like to have a set of dropdown filters so the top one filters the returned data but LEVEL then the second one by STYLE (keeping the level the same as selected) and third option by HANDLE (again keeping the previous options in mind)
Is this possible to do. I am out of my depth a bit but trying to learn as I go.
Thanks for your time guys
Sure, it's possible. I've prepared a self explanatory code snippet that should help you out.
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope',
function($scope) {
$scope.model = {
selectedStyle: "",
selectedLevel: "",
filterObject: { style : "", level : ""},
recordDetails: undefined,
options: {
styles: ["", "style1", "style2"],
levels: ["", "level1", "level2"]
},
data: [{
"id": 1,
"level": "level1",
"style": "style1",
"price": 100
}, {
"id": 2,
"level": "level2",
"style": "style2",
"price": 200
}, {
"id": 3,
"level": "level1",
"style": "style2",
"price": 300
}, {
"id": 4,
"level": "level2",
"style": "style1",
"price": 400
}]
};
$scope.showDetails = function (record) {
$scope.model.recordDetails = record;
}
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<select name="styleSelect" id="styleSelect" ng-options="option for option in model.options.styles" ng-model="model.filterObject.style"></select>
<select name="levelSelect" id="levelSelect" ng-options="option for option in model.options.levels" ng-model="model.filterObject.level"></select>
Current filter object: {{model.filterObject}}
<div ng-repeat="record in model.data | filter:model.filterObject">
<a href="#" ng-click="showDetails(record)">
<ul>
<li>{{record.id}}</li>
<li>{{record.level}}</li>
<li>{{record.style}}</li>
</ul>
</a>
</div>
<div>
Record details:
{{model.recordDetails}}
</div>
</div>
Please let me know whether anything needs further explanation.
I forked a normalization example from Kato's fiddle and updated it to the current version of AngularFire and Firebase, you can see it here. I tested around a bit to get a better understanding of how $firebaseObject and $firebaseArray work and I really get a hang of it.
Except the toJSON from $firebaseObject.
So I have this little code in the controller:
$scope.singlePost = singleMergedPost('post2');
console.log('singlePost', $scope.singlePost);
The output normally is:
{
"postData": {
"bla": "blubb",
"dateCreated": 1397584465,
"title": "Another cool website",
"upvotes": 1,
"url": "http://www.google.com",
"user": "simplelogin:2"
},
"userData": {
"email": "kato#firebase.com",
"jobTitle": "Awesome Dude",
"name": "Kato Richardson"
}
}
But when I add toJSON to $extend the output is:
{
"bla": "blubb",
"dateCreated": 1397584465,
"title": "Another cool website",
"upvotes": 1,
"url": "http://www.google.com",
"user": "simplelogin:2"
}
$scope.singlePost actually contains the same data, but I am wondering about:
Why is toJSON even called here, although I haven't sent back any data to the server (at least it looks like from my point of view) yet.
Why does <pre ng-bind="singlePost | json"></pre> only show the postData data?
1. toJSON
.toJSON() is called to strip the properties and methods of a $firebaseObject or $firebaseArray that start with $ or $$. It serializes the object to valid JSON data.
This is done to display the data in the <pre> div for debugging, without the $ methods.
See this answer from Kato.
2. Difference in data
<pre ng-bind="singlePost | json"></pre> only shows the postData because only the postData property of this (the $firebaseObject) is passed to the .toJSON() method in the line $firebaseUtils.toJSON(this.postData);
Compared to passing the whole object (including postData and userData properties) in console.log('singlePost', $scope.singlePost);
If you log $scope.singlePost.postData, you should see the same result.
I keep running into some confusing solutions and unclear ways to wrap items that match into a div using backbone.
I am just building a simple example for myself, and would like to nest all models in a collection that have the same attribute team, using a comparator works well in organizing the list, but for the life of me I can't find a clear solution to wrapping each so that I have more control over the list of players inside the team.
There has to be a clear easy solution for a beginner like me. I really just want to keep things as clean and simple as possible. My desired html result looks like below.
<div class="pacers">
<li>Paul</li>
<li>Roy</li>
</div>
<div class="bulls">
<li>Kirk</li>
<li>Taj</li>
</div>
Based on a backbone friendly json array like below.
[
{
"name": "Paul",
"team": "pacers"
},
{
"name": "Kirk",
"team": "bulls"
},
{
"firstname": "George",
"team": "pacers"
},
{
"name": "Taj",
"team": "bulls"
}
]
So using a comparator is awesome I just write this comparator : 'team' and it handles the list order for me, cool, but I dont have much control I would like to wrap the list in a more hierarchical system.
Another approach:
If you are using underscore's templates this could be one way of doing it. You can use underscore's groupBy function to group the list based on teams.
var teams = [
{
"name": "Paul",
"team": "pacers"
},
{
"name": "Kirk",
"team": "bulls"
},
{
"firstname": "George",
"team": "pacers"
},
{
"name": "Taj",
"team": "bulls"
}
];
var groupedList = _.groupBy(list, function(l){
return l.team;
});
console.log(JSON.stringify(groupedList));
This is how it would be grouped.
{
"pacers": [
{
"name": "Paul",
"team": "pacers"
},
{
"firstname": "George",
"team": "pacers"
}
],
"bulls": [
{
"name": "Kirk",
"team": "bulls"
},
{
"name": "Taj",
"team": "bulls"
}
]
}
You can then use for each loop and in template and generate HTML in following way. The groupedList is passed as teams to below template.
<%
_.each(teams, function(team, teamName){
%>
<div class="<%=teamName%>">
<%
_.each(team, function(player){
%>
<li><%=player.name%></li>
<%
});
%>
</div>
<%
});
%>
This would generate the HTML the way you expected.
NOTE:
The code snippets are given considering underscore templating, you might have to make changes based on what you use. Hope it helps.
Correct me if I am wrong the problem being described relates more to controlling the contents of each item in relation to it's model as well as how to simply render them in groups.
1) Niranjan has covered grouping out the data into separate lists but remember that this list returned is not a Backbone construct.
2) As per the manual the '_.groupBy' method should be available to you via the collection i.e.:
myCollection.groupBy(etc);
3) I would personally consider mapping the results of the groupBy back into models and pass each and every model into a separate view and render them from within the main list view.
var CollectionView = Backbone.View.extend({
initialize : function () {
// Note: I am pretending that you have a real collection.
this.collection.fetch().then(
this.addAll(true);
);
}
addOne : function (model) {
// call .render individual template items here for each model.
var view = new ItemView(model);
this.$el.append(view.render();
},
addAll : function (groupOpts) {
var col = this.collection;
if(groupOpts === true) {
// Do grouping (or do it in the model). Maybe put back into new collection?
}
_.each(col, function(model) {
this.addOne(model);
}, this);
},
render : function () {
// Render your template here.
}
});
var ItemView = Backbone.View.extend({
render : function () {
}
});
Not a complete example but that's the general pattern I would follow when attempting the same thing. Having an individual view/model for each item, in my opinion, gives you more control.
This could be handled in a pretty crazy view template (depends on your template language)... or you could use a simpler template/view and just make some more crazy collection queries (first using a pluck to get the team, de-dupping that array, then running some where's for each of the teams... but you can see how this gets crazy)
I'd vote for the view and view template should handle this... what are you using? Jade? Mustache?
Something like this - logical psuedo code here since I don't know your template language:
var team;
forEach player in players
if(!team) {
set team = player.team
print open holder and then the first row
} (team !== player.team {
set team = player.team
print close of previous holder, then open holder and then the first row of new team
} else {
print just the player row
}
Even so, you can see how this is a bit dirty in and of itself... but what you are describing is a view/presentation concern, and you can do it here with no new additional loops and maps and wheres (like you'd have to do if you did it in the data layer before calling the views)