Manipulating JSON data with Angular's conditional styling

Looking to convert my small jquery app into AngularJs, seeking advice on the feasibility of doing so. Currently, the app makes ajax calls to retrieve Json data which is then parsed and displayed in the dom.

The challenge lies in the variety of json properties - simple strings, arrays, or nested objects. When parsing the Json, I format it accordingly - creating tables for arrays, calculating string lengths, and outputting the results to the dom.

While achievable with jquery, the process is somewhat verbose. Curious to know if a similar functionality can be replicated using AngularJs.

$.each(data.ALLIMG, function(i, image) {
    if(image.alt){
        $("#imagesDetail").append("<li>ALT:" + image.alt + " SRC: ");
        $("#imagesDetail").append(image.src + "</li>");
        totalAltImg++;
    }
});
$("#text").append("<p>" + data.TEXT + "</p>");
$("#text").append("<p><b>Length: </b>" + data.TEXT.LENGTH + " character(s)</p>");

In angular syntax, it seems like I should use something like {{text}}. But how do I handle arrays to display as tables or lists?

Answer №1

In this illustration, you will find a complete working example showcasing how to utilize the ng-show directive for testing the presence of a property. Although in this instance, it renders hidden, it offers a simpler alternative to using a filter. Additionally, a straightforward demonstration of a filter has been provided. I made an assumption that you wished to calculate the character count of the data.TEXT.

To view the demonstration, visit: http://plnkr.co/br2M4GXrDENd4rLkDBho

<!-- Utilizing ngshow -->
<ul id="imagesDetail">
  <li ng-repeat="image in data.ALLIMG" ng-show="image.alt">
     ALT: {{image.alt}} SRC: {{image.src}}
  </li>
</ul>
<!-- Implementation with filter outlined below -->
<ul id="imagesDetail2">
  <li ng-repeat="image in data.ALLIMG | filter:hasAlt" >
    ALT: {{image.alt}} SRC: {{image.src}}
  </li>
</ul>

<div id="text">
  <p>{{data.TEXT}}</p>
  <p><b>Length: </b> + {{data.TEXT.length}} character(s)</p>
</div>

The controller filter is as follows:

 $scope.hasAlt = function(image) {
  return image.alt!==undefined;
 }

Answer №2

This should be displayed as follows:

<ul>
  <li ng-repeat='picture in data.ALLIMG'> ALT: {{picture.alt}} {{picture.src}}</li>
</ul>

In case you need to eliminate incorrect data (similar to what is shown in your example), you can set up a filter condition in your controller:

<ul>
  <li ng-repeat='picture in data.ALLIMG| filter:properPictures'> 
     ALT: {{picture.alt}} {{picture.src}}</li>
</ul>

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

Manipulating DropDownList Attributes in ASP.NET using JavaScript

I am facing an issue with populating a Dropdownlist control on my ASCX page. <asp:DropDownList ID="demoddl" runat="server" onchange="apply(this.options[this.selectedIndex].value,event)" onclick="borderColorChange(this.id, 'Click')" onblur="bo ...

Deleting an element from an array renders the iterator invalid

Looking for a solution in AngularJS to eliminate all categories with a count of 0 from the categories array. // removing categories with zero count i = 0; angular.forEach( $scope.categories, function( category ) { if( category.count == 0) ...

Choose a collection of elements and encase them within a <div> tag

I am currently working on creating a greasemonkey script for a webpage that has a rather challenging structure. My goal is to show and hide different entries, but the content is formatted like this: <a name="first"/> <h3>First</h3> Some ...

What is the best way to make one page disappear and replace it with a pop-up from

I am currently encountering an issue with my sign-in and registration pages. I have a pop-up page that includes both the sign-in and register tabs. When clicking on the register tab, the sign-in page is supposed to disappear and the registration page shoul ...

Maintain the state of the previous page in Vue to ensure continuity

Currently in the process of creating a small PWA to simulate an Android app, I have discovered Vuejs. However, I encountered an issue that has proven difficult to resolve. While scrolling through lists on the homepage for movies, TV shows, or news, clicki ...

Verifying the authenticity of a Stripe discount code

My goal is to allow users to apply a coupon code on my website, triggering a check in the Stripe dashboard. Currently, I have implemented the following code snippet, but I am facing an issue with transferring the validCoupon data from the client side to th ...

JavaScript API for Tableau

Could you please clarify the functions described below? newViz = createTableauViz(containerDiv, url, options); function listenForMarkSelection() { newViz.addEventListener(tableau.TableauEventName.MARKS_SELECTION, handleMarksSelection); } funct ...

Failing to complete a field in the form does not generate an error message when submitted [AngularJS]

My code is designed to display an error message if the user clicks the submit button without filling in a field. However, the functionality is currently not working as intended. <form name="loginForm" ng-submit="loginForm.$valid && login()" n ...

Typescript: Ways to fix the error 'rxjs/Rx does not have any exported member 'SubscriptionLike'

I'm attempting to replicate the steps outlined in this tutorial found here https://www.youtube.com/watch?v=gxCu5TEmxXE. However, upon running tsc -p, I encounter an error. Is there a specific import that I am missing? ERROR: node_modules/@angular/co ...

Issues with the initial drop functionality in jQuery UI

How come the jQuery code does not work properly on the first drop? $(".drag").draggable({ revert: 'invalid', drag: function(event, ui) { $(this).addClass('valid'); } }); $("#droppable").droppable({ accept: '.valid&apos ...

Include a class in ul > li elements upon page load in Angular4

I attempted to add a class to each "li" element in an Angular4 page, but the class was not applied. Here is the relevant HTML code: <ul class="pagination"> <button class="previous" (click)="previous()">Previous</button> <button ...

Stop the form from submitting when the Enter key is pressed

I am experiencing an issue with my form that contains around 10 input text boxes. When I press the enter key from an input text box, it skips the text boxes in between and goes directly to the submit button. This problem occurs only when using the keyboard ...

Unable to receive parameters in Java Servlet POST request action

Recently, I decided to delve into the world of Tomcat and Servlets, coming from a background in IIS, C#, and MVC. To enhance my project, I am also incorporating AngularJS and Guice. I have created a Servlet with a single method: @Singleton @SuppressWarn ...

The Bootstrap carousel feature allows you to track the duration each image is displayed

Is there a way to track the amount of time a specific image is visible to the user in a Bootstrap 5 carousel? I'm interested in measuring how long a user views a particular image, such as a product image, in the carousel. For example, I'm lookin ...

React Alert: Please be advised that whitespace text nodes are not allowed as children of <tr> elements

Currently, I am encountering an error message regarding the spaces left in . Despite my efforts to search for a solution on Stack Overflow, I have been unable to find one because my project does not contain any or table elements due to it being built with ...

Unable to execute query with $gt and $size in Mongoose

Below is my mongoose query along with the router: router.get('/reportsRegular', function(req,res,next){ Question.find({reports: {$size: {$gt: 0}}, checked: false}).sort({reports: -1}).limit(20).exec(function(err,results){ console.log(result ...

Error message indicating that the preflight request failed access control check in Angular 5 with JWT OAuth integration

After spending hours reading through several posts, I have yet to find a solution to a very common problem. It seems that in order for my JavaScript code to access the resource, the server must include the Access-Control-Allow-Origin header in the response ...

The React.js search feature consistently retrieves identical content every time

I am currently working on a project to create a search engine using React.js, specifically to search for GIPHY gifs through their API. However, I have encountered an issue where the gifs displayed do not update when I type in new words after erasing the pr ...

Is there a way to retrieve a particular object from the state and access one of its elements?

I have a component called Tweets.js: import React, {Component} from "react"; export default class Tweets extends Component { constructor(props) { super(props); this.state = {tweets: [], users: []}; } componentDi ...

Executing a JavaScript function when a column in a Fusion Chart is clicked

I have two div elements in HTML and I would like to have div2 load when div1 is clicked. Additionally, whenever div2 loads, a back button should also appear to return to div1. Is there a way to achieve this using HTML? <td background="images/bgTd.gif ...