Exploring Angular.JS: How to Access Sub-Arrays and Parse Keys

Trying my hand at building something with Angular for the first time, I'm facing an issue with retrieving JSON data.

The data is fetched from a SQL database in JSON format and passed to a template using Angular route:

.when('/tasks/:TaskID',{
    templateUrl: 'template/task_data_template.html',
    controller:"showTaskData",
    controllerAs: 'STD'
})

The showTaskData function is defined as follows:

angular.module('moonDive').controller('showTaskData',function($http,$routeParams){

var store = this; 

store.tasks= [];

json_Url = 'api/tasks_data.php?TaskID=' + $routeParams.TaskID;


$http.get(json_Url).success(function(data){
    store.tasks = data; 
})});

The structure of my data is as follows:

This can be accessed from the HTML template by:

{{STD.tasks[1]}}

Which returns the data in "JSON" format:

{
    "ActionID": "1",
    "Taskref": "1",
    "Ast1_1": "",
    "Ast2_1": "Start EVA watch\nopen           hatch\nAssist CDR",
    "Ast3_1": "",
    "Ast1_2": "Egress cabin to LM porch\nReceive &      jetttison bag\nReceive ETB/LEC",
    "Ast2_2": "Deploy CDR PLSS antenna\nHand jettison      bag to CDR\nHand ETB/LEC to CDR",
    "Ast3_2": "",
    "Ast1_3": "Descend lander to top rung\nUnlock and deploy MESA\nLower ETB on LEC",
    "Ast2_3": "Tape recorder -off\nVerify voice signals level and uitlity floo [......]"
}

Now, aiming to create a table with two columns (ast1, ast2) and X number of rows for X tasks. Unsure where to start, I attempted the following:

<table class="bordered hoverable responsive-table">
<tbody>

<tr ng-repeat="boo in STD.tasks[1]">
<td style=" color: blue;" ng-if="$odd"> {{boo}}</td>
<td style="color:red" ng-if="$even"> {{boo}}</td>
</tr>
</tbody>
</table>

Unfortunately, the above code did not work as expected. It displays all the information in what appears to be a random order.

I wish to remove rows with "1"; typically, I would use ng-if="boo.NameOfTheRow", but in this scenario, I do not have access to the name. How can I delete unnecessary data and organize my data by Astr1 and 2 (for columns) and task 1 to X (for rows)?

Thank you!

PS: The desired output should resemble:

<table>

<thead>
    <td> task </td>
    <td> Astr 1 </td>
    <td> Astr 2 </td>
    <td> Astr 3 </td>
</thead>

<tbody> 
<tr>
    <td> 1</td>
    <td> {{STD.tasks[1].Ast1_1}} </td>
    <td> {{STD.tasks[1].Ast2_1}}</td>
    <td>{{STD.tasks[1].Ast3_1}}   </td>
</tr>
<tr>
    <td> 2</td>
    <td> {{STD.tasks[1].Ast1_2}} </td>
    <td> {{STD.tasks[1].Ast2_2}}</td>
    <td>{{STD.tasks[1].Ast3_2}}   </td>
</tr>

<tr>
    <td> 3</td>
    <td> {{STD.tasks[1].Ast1_3}} </td>
    <td> {{STD.tasks[1].Ast2_3}}</td>
    <td>{{STD.tasks[1].Ast3_3}}   </td>
</tr>

....
<tr>
    <td> 7</td>
    <td> {{STD.tasks[1].Ast1_7}} </td>
    <td> {{STD.tasks[1].Ast2_7}}</td>
    <td>{{STD.tasks[1].Ast3_7}}   </td>
</tr>

    </tbody></table>

The data should display as:

Answer №1

When dealing with an array of entries like STD.tasks, it is important to update your ng-repeat statement to ng-repeat="boo in STD.tasks".

Typically, you will receive JSON data in the following format:

[
  {"field":"value", "field2": "value"},
  {"field":"value", "field2": "value"},
  {"field":"value", "field2": "value"},
  ...
]

Ensure that ng-repeat iterates over each value in the array rather than just the first item. Currently, it may be repeating over each property within the object.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Preserve jQuery-enhanced webpage changes permanently

I am looking to permanently save modifications made on an HTML page using JQuery. I have come across suggestions about achieving this by sending an Ajax call and storing the data in a database table. However, I am unsure about what exactly needs to be save ...

What is the simplest method for invoking a C# function from JavaScript?

I am facing an issue with a LinkButton control in my project. I need to attach a c# method to it, but when I add the control to the page using parse control function, it changes the call to javascript and results in an undefined error. I have been trying t ...

What occurs when the update function returned by React.useState() is invoked?

Just recently, I delved into the world of React hooks and decided to implement a small feature using them. The feature enables hidden texts to be displayed when users click on hyperlinks. Although I managed to make the code work, it appears that there are ...

Utilize the power of modern Javascript to extract and display data from a JSON file by mapping an array and adding it

I've been attempting to construct a table from a JSON file by utilizing the map method in React. I've experimented with two approaches - one using map and the other using a for loop - but so far, I haven't been successful in getting the desi ...

What is the best way to export Class methods as independent functions in TypeScript that can be dynamically assigned?

As I work on rewriting an old NPM module into TypeScript, I encountered an intriguing challenge. The existing module is structured like this - 1.1 my-module.js export function init(options) { //initialize module } export function doStuff(params) { ...

Converting a JSON object into an array with JQ

Looking to transform a map of objects into an array using jq Input: { "fish-chips": { "likeDislikeRatio": ["80%", "20%"], "country": ["BRIT_FOOD","USA_FOOD"] }, "saus ...

Is it necessary to test the main.js file in Vue.js project?

While performing unit tests on components is acceptable, after running coverage analysis I have noticed that certain lines of code in the main.js file remain uncovered. This raises the question: should the main.js file also be included in testing? Specifi ...

What is the process for accessing an uploaded file in a server-side Classic ASP page?

I'm attempting to use Ajax to upload a file to a server-side script in classic ASP. Here is the relevant HTML and JavaScript code: <input type="file" id="fileInput" /> and function saveToServer(file) { const fd = new FormData(); fd.a ...

Determine if an array of objects within React JS contains additional objects

I need assistance in displaying the <div className="songs-list-header-col">Album</div> only if the tracks array contains the artist property as an object. In cases where the artist is not an object, I do not want to display the <di ...

Using JavaScript, delete a class from an element

I am looking for a way to remove a specific class attribute from all elements on a webpage. The challenge is that I only have the class name as a reference, and cannot use any other identifiers like id or another class. Additionally, I cannot rely on JavaS ...

ReactJs - SyntaxError: The JSX content is not properly terminated

I'm just starting out with ReactJs and have come across an issue that I can't seem to figure out. Here's my code snippet: var ListComponent = React.createClass({ render: function() { return ( <li>{this.props.va ...

The React-loadable alert indicated a discrepancy in the text content

Utilizing react-loadable for dynamic JS module loading is part of my process. With server-side rendering already set up and functioning correctly for react-loadable, I am encountering an issue on the client side. Upon page load, a warning message appears i ...

Having trouble with routing nesting in react-router v4?

I find myself in the following situation: <Wrapper> <Container> <Route exact path="/" component={UserListing} /> <Route path="/user/:id" component={UserDetails} /> <Route exact path="(/|/user/\d+)" comp ...

AngularJS does not allow empty spaces in textarea inputs

I am working on a form that includes a textarea element for users to input descriptions, however it does not allow any empty spaces. Users can only input alphanumeric and numeric characters, but no spaces. <textarea class="form-control" rows="4" maxl ...

What are the best techniques for distinguishing the selected selector in jQuery?

$('#select_id1, #select_id2, #select_id3').change(function() { // Depending on which select element has changed, 'str' should be set accordingly. // For '#select_id1', 'str' should be equal to 'select_id ...

TS1086: Attempting to declare an accessor within an ambient context is not allowed

While using Angular, I encountered the error TS1086: An accessor cannot be declared in an ambient context. when using Javascript getters and setters in this Abstract Typescript class. Here is the code snippet causing the issue: /** * The current id ...

Refreshing Data on Vuetify Range Slider

My goal is to update the value as the slider position changes. [codepen]https://codepen.io/JakeHenshall/pen/WLezNg <div id="app"> <v-app id="inspire"> <v-card flat color="transparent"> <v-subheader>Tick labels</v-subheade ...

Sails encountering CORS preflight error due to cross-origin request

I am new to creating hybrid apps and have been following some tutorials. However, I encountered these errors on my browser console: Refused to load the script 'http://192.168.1.142:35729/livereload.js?snipver=1' due to Content Security Policy di ...

Find the index of the element that was clicked by utilizing pure JavaScript

I am struggling to find the index of the element that was clicked. Can anyone help me with this? for (i = 0; i < document.getElementById('my_div').children.length; i++) { document.getElementById('my_div').children[i].onclick = f ...

Having trouble getting an HTML form to function with Ajax and PHP?

Seeking assistance from anyone who can lend a hand. I am delving into the complexities of Ajax, and I'm encountering issues where it seems like the script is being completely ignored or perhaps I'm just making a rookie mistake. Prior to display ...