Populate AngularJS {{expression}} within ng-repeat using a second array - javascript

I'm completely rebuilding my website (originally hacked together with Wordpress) using Laravel and AngularJS. It's been a massive learning experience and I think I'm nearly there but for one problem.
On my site 'schemes' (or courses) are made up of 'units' which are made up of 'lessons'. Retrieving this data is fine, using Eloquent I retrieve valid JSON like this made up example...
[
{
"id": "1", //Scheme Id
"title": "Sports",
"description": "This is a Sports course!",
"units": [
{
"id": "1",
"title": "Tennis",
"lessons": [
{
"id": "6",
"title": "Serving"
},
{
"id": "7",
"title": "Hitting the ball with top-spin"
}
]
},
{
"id": "2",
"title": "Athletics",
"lessons": [
{
"id": "1",
"title": "Long Jump"
},
{
"id": "2",
"title": "Hurdling Technique"
}
]
},
{
"id": "4",
"title": "Golf",
"lessons": [
{
"id": "4",
"title": "Pitching"
},
{
"id": "5",
"title": "Putting"
}
]
}
]
}
....
]
Separately I have a simple array of completed lesson ids for a particular user like this...
[2, 6, 8, 9] ///User has completed lessons with ids of 2,6,8 and 9
In my view I'm using nested ng-repeat loops like so...
...
<div ng-controller="SchemesController">
<div ng-repeat="scheme in schemes">
<h1>{{scheme.title}}</h1>
<div ng-repeat="unit in scheme.units">
<h3>{{unit.title}}</h3>
<div ng-repeat="lesson in unit.lessons">
<div>{{lesson.title}}: {{status}}</div>
</div>
</div>
</div>
</div><!--[end of ng-controller="SchemesController"]-->
....
SchemesController (v simple!) looks like this...
var app = angular.module('schemesApp', []);
app.controller('SchemesController', function($scope){
$scope.schemes=jsonData;
});
The problem is I have no idea how to populate the {{status}} field which I want to state simply 'Complete' or 'Incomplete. I investigated whether I could somehow add this info to my original array like this...
"lessons": [
{
"id": "6",
"title": "Serving",
"status": "Complete" //populated somehow
},
{
"id": "7",
"title": "Hitting the ball with top-spin",
}
]
but I got nowhere slowly. Is there a way to do this (I've played around with underscore.js and felt this could help?).
Or do I populate {{status}} from creating and calling a javascript function?!?
ANY help that anyone could offer would be incredible. I'm a school teacher and for some sadistic reason I find a bit of programming/web design a fun use of my spare time so I apologise if this is a stupid question. THANKS in advance!!!
btw if anyone has a better 'title' for this question then please let me know.

I'm assuming you don't need to persist the status back to the database...
This is where you're having the problem:
<div>{{lesson.title}}: {{status}}</div>
You really don't need to store the status in your data model, because it's just used for presentation purposes.
Let's say your array of completed lessons is defined like this:
$scope.completedLessons = [1, 2, 3, 4, 5] // Or however you'd assign it
You need to create a function in your scope like this:
$scope.isLessonCompleted = function(lessonId) {
return $scope.completedLessons.indexOf(lessonId) > -1;
};
Then you need to change the html from above to this:
<div>{{lesson.title}}: {{isLessonCompleted(lesson.id) && 'Complete' || 'Incomplete'}}</div>

If lessons are also a model and each lesson should have a status, which isn't a column/field in your table but is something you'll add logic to determine, you could add a custom model accessor by adding the following to your models/Lesson.php:
// Append custom accessor attributes
protected $appends = ['status'];
public function getStatusAttribute() {
// Add logic here
return 'Complete';
}
This way, when you use Eloquent to retrieve your data, you'll also see a status attribute as part of the object, so you could then access it as usual $lesson->status (PHP) or lesson.status (JS).
For more information, see the official Laravel documentation on accessors and mutators

Related

Displaying Nested Objects (Numeric) After Making Service Call

I'm currently having an issue accessing nested objects that are referred to through numbers. I made a service call to retrieve a JSON object, and then mapped each field to another object. I'll be using this object to display each field in the HTML.
My problem is occurring when I reach the nested objects. Here's an example :
{
"name": {
"title": "mr",
"first": "something",
"last": "something"
},
"role": "something",
"projects": {
"0": {
"title": "something",
"account": "something",
"steps": {
"total": 30,
"completed": 28
},
"dueDate": "2021-07-19 09:00:00",
"status": "fine"
},
"1": {
"title": "something",
"account": "something",
"steps": {
"total": 10,
"completed": 5
},
"dueDate": "2021-07-20 09:00:00",
"status": "fine"
},
}
}
The projects field gets tricky when trying to display all projects in the HTML. At the moment, I've created a person variable initialized to an empty array, and I add all of the fields from t he subscription to it. To solve this problem, I figured I should create a separate variable such as projects: any = []; and then set it to a new field in the person variable. Then iterate through it using an *ngFor, and display every project. Something like this
<li *ngFor="let project of person.projects">
{{ project }}
</li>
However that approach still doesn't reach the nested fields. How do I access the numbered objects here, and generally iterate through all of the nested fields?
Any advice will be very helpful. Thank you in advance.
I think you are looking for the KeyValuePipe
You would use it like this:
<li *ngFor="let item of person.projects | keyvalue">
{{ item.value }}
</li>
But based on your comment on doing this for more nested values, it might be worth flattening the data a bit in the component to simplify the template logic.

Set list items in ng-model in a dropdownmenu angularjs

currently I stuck with an angularjs problem. The following scenario:
I have a Game entity and a Team entity. One Game can hold multiple Team objects. (ManyToMany Relationship)
In my frontend application I want to add a new Game with optional Teams. For the Teams I decided to use two dropdown-menus (each menu for one team).
Now I am not able to give the ng-model the correct values.
I tried something like this but it might be wrong:
<select class="form-control" ng-options="team.teamname for team in teams
track by team.id" ng-model="game.teams[0]">
<option value="" selected>-- No Team --</option>
</select>
<select class="form-control" ng-options="team.teamname for team in teams
track by team.id" ng-model="game.teams[1]">
<option value="" selected>-- No Team --</option>
</select>
As soon as I click the save button i get an error message "400: Unable to process JSON":
Possibly unhandled rejection: {"data":{"code":400,"message":"Unable to process JSON"},"status":400,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","data":{"teams":{"0":{"id":1,"games":[{"id":1,"date":20180810}],"teamname":"BVB"},"1":{"id":2,"games":[{"id":1,"date":20180810}],"teamname":"FCB"}},"date":"20180810"},"url":"/api/games","headers":{"Accept":"application/json, text/plain, */*","Content-Type":"application/json;charset=utf-8"}},"statusText":"Bad Request"}
When creating the two Teams for a Game with Postman it works:
{
"date": 20180810,
"teams": [{"id": 1}, {"id": 2}]
}
Output:
{
"id": 1,
"date": 20180810,
"teams": [
{
"id": 1,
"games": [
{
"id": 1,
"date": 20180810
}
],
"teamname": "BVB"
},
{
"id": 2,
"games": [
{
"id": 1,
"date": 20180810
}
],
"teamname": "FCB"
}
]
}
Any suggestions how to set the ng-model (Game) with the values of the first and second dropdown-menus? thanks
I have added a screenshot of the form that i want to have:
If i understand well, when you do the request with postman, you send this:
{
"date": 20180810,
"teams": [{"id": 1}, {"id": 2}]
}
But your angular form is actually sending this:
{
"date": "20180810"
"teams": {
"0": {
"id": 1,
"games": [
{
"id": 1,
"date": 20180810
}
],
"teamname": "BVB"
},
"1": {
"id": 2,
"games": [
{
"id": 1,
"date": 20180810
}
],
"teamname": "FCB"
}
}
}
While the date looks fine, your teams is an object but your backend is expecting an array. You also have additional informations in your teams (like games and teamname, but i can't know if this is a problem for your backend.
Most of the time this kind of problems with Angularjs are not in the html template but in the controller. In your controller you should have something like this:
scope.game = {
date: 'something',
teams: []
};
I think your problem is that you don't initialize scope.game.teams as an array properly. So ng-model just initliaze it by itself with an object.
From what i gather you want to add multiple teams for each game, follow the checklist model, its probably what you want, https://vitalets.github.io/checklist-model/ from there you can pass the server a list of games for each team

JSON list optimization

I want to create a JSON API that returns a list of objects. Each object has an id, a name and some other information. API is consumed using JavaScript.
The natural options for my JSON output seems to be:
"myList": [
{
"id": 1,
"name": "object1",
"details": {}
},
{
"id": 2,
"name": "object2",
"details": {}
},
{
"id": 3,
"name": "object3",
"details": {}
},
]
Now let's imagine that I use my API to get all the objects but want to first do something with id2 then something else with id1 and id3.
Then I may be interested to be able to directly get the object for a specific id:
"myList": {
"1": {
"name": "object1",
"details": {}
},
"2": {
"name": "object2",
"details": {}
},
"3": {
"name": "object3",
"details": {}
},
}
This second option may be less natural when somewhere else in the code I want to simply loop through all the elements.
Is there a good practice for these use cases when the API is used for both looping through all elements and sometime using specific elements only (without doing a dedicated call for each element)?
In your example you've changed the ID value from 1 to id1. This would make operating on the data a bit annoying, because you have to add and remove id all the time.
If you didn't do that, and you were relying on the sorted order of the object, you may be in for a surprise, depending on JS engine:
var source = JSON.stringify({z: "first", a: "second", 0: "third"});
var parsed = JSON.parse(source);
console.log(Object.keys(parsed));
// ["0", "z", "a"]
My experience is to work with arrays on the transport layer and index the data (i.e. convert array to map) when required.

Angularjs - How to call an array inside JSON data to html

I have a little problem.. I've got this JSON data:
[
{
"students": {
"student_id": "2",
"student_school": "1",
"student_name": "Charles"
},
"parents": [
{
"parent_id": "2",
"parent_school": "1",
"parent_name": "Tim"
}
]
},
{
"students": {
"student_id": "3",
"student_school": "1",
"student_name": "Johnny"
},
"parents": [
{
"parent_id": "3",
"parent_school": "1",
"parent_name": "Kate"
}
]
}
]
The problem is that I try to call to my html page by angular:
{{student.student.student_name}}
Yeah it works but when I want to call the parents data it doesn´t...
{{student.parents.parent_name}}
Simply:
<div ng-repeat="student in data">
{{student.students.student_name}}
{{student.parents[0].parent_name}}
</div>
Or define function in scope called for example getParentDescription and than
<div ng-repeat="student in data">
{{student.students.student_name}}
{{getParentDescription(student)}}
</div>
Because parents is an array. You must specify the index (0 in your case). See the response here : How to get value from a nested JSON array in AngularJS template?
You can't access child scopes directly from parents. See the comment by Vittorio suggesting<ng-repeat="child in parent.children"/> also Binding to Primitives
I'm guessing student is from an ng-repeat where you go through each object in the array.
Take a closer look at your JSON. While "students": {} points to an object, "parents": [] points to an array. Fix your JSON and it'll be fine

Javascript looping through elements and adding to table

I'm having trouble finding a solution that will help me loop through a bunch of elements and putting the chosen values into a table. I've been able to withdraw some values but the method isn't dynamic.
Here is an example:
var Table = {
"credit": {
"link": "site link",
"logoUrl": "logo url",
"message": "message"
},
"groups": [
{
"labels": [
{
"name": "Western Conference",
"type": "conference"
},
{
"name": "Central Division",
"type": "division"
}
],
"standings": [
{
"stats": [
{
"name": "gp",
"value": 20
},
{
"name": "w",
"value": 17
},
{
"name": "l",
"value": 0
},
{
"name": "gf",
"value": 64
},
{
"name": "ga",
"value": 37
},
{
"name": "gd",
"value": 27
},
{
"name": "pts",
"value": 37
}
],
"team": {
"id": 12345,
"link": "team link",
"name": "team name",
"shortName": "team"
}
},
This is the structure of the elements. So far I've used this:
document.getElementById("sGamesPlayed").innerHTML=Table.groups[0].standings[0].stats[0].value;
to withdraw values. However there are more teams, stats and divisions so I would need some kind of loop to go through the elements and put the into a dynamic table.
I would consider you to look at http://underscorejs.org/.
it provides a bunch of utility functions that could help you,
for example, _.each() helps you loop through JSON properties.
for the sample objects you've given (after completing the missing brackets at the end),
_.each(Table.groups[0].standings[0].stats, function(stats){
console.log(stats['name']+","+stats['value'])
})
gives me:
gp,20
w,17
l,0
gf,64
ga,37
gd,27
pts,37
how it works is that you provide the object you want as the first argument and the function that you give as the second argument will be called with each element of the first argument (Assuming it is a list).
I would also urge you to look at underscore templating that you can use to render your table where i put the console.log :
http://net.tutsplus.com/tutorials/javascript-ajax/getting-cozy-with-underscore-js/
http://scriptble.com/2011/01/28/underscore-js-templates/
I guess your question is about filtering the values of the array standings. In order to do that you can use the jQuery grep function (if you want to use jQuery).
For example you can write:
var arr = $.grep(Table.groups[0].standings[0].stats, function(d){return d.value>25})
Which will give
arr = [{"name": "gf","value": 64}, {"name": "ga", "value": 37},{"name": "gd", "value": 27},{"name": "pts", "value": 37}]
If this is not what you meant, can you please create a jsFiddle with a sample of what you want?
Depending on what you want to do with the results, you can go over the object using a scheme like:
var groups, standings, stats, value;
groups = Table.groups;
// Do stuff with groups
for (var i=0, iLen=groups.length; i<iLen; i++) {
standings = groups[i].standings;
// Do stuff with standings
for (var j=0, jLen=standings.length; j<jLen; j++) {
stats = standings[j];
// Do stuff with stats
for (var k=0, kLen=stats.length; k<kLen; k++) {
value = stats[k].value;
// Do stuff with value
}
}
}
Of course I have no idea what the data is for, what the overall structure is or how you want to present it. But if you have deeply nested data, all you can do is dig into it. You might be able to write a recursive function, but it might also become very difficult to maintain if the data structure is complex.

Categories

Resources