Unveiling the Power of AngularJS for Parsing JSON Data

A list of images is being generated in a table-like structure using the code snippet below. Each image represents a cell in this table, with its ID specifying its row and column position.

<ul>
   <li class="row">
      <ul>
            <li class="photo" id="photo-1A">1A</li>
            <li class="photo" id="photo-1B">1B</li>
            <li class="photo" id="photo-1C">1C</li>
            <li class="photo" id="photo-1D">1D</li>
            <li class="photo" id="photo-2A">2A</li>
            <li class="photo" id="photo-2B">2B</li>
            <li class="photo" id="photo-2C">2C</li>
            <li class="photo" id="photo-2D">2D</li>
            <li class="photo" id="photo-3A">3A</li>
            <li class="photo" id="photo-3B">3B</li>
            <li class="photo" id="photo-3C">3C</li>
            <li class="photo" id="photo-3D">3D</li>
      </ul>
   </li>
</ul>

I have a JSON object that indicates whether each photo is available or not. The JSON string contains information like:

[{"row":1,"position":"A","available":true},{"row":1,"position":"B","available":false},{"row":1,"position":"C","available":false},{"row":1,"position":"D","available":false},{"row":2,"position":"A","available":true},{"row":2,"position":"B","available":false},{"row":2,"position":"C","available":false},{"row":2,"position":"D","available":false},{"row":3,"position":"A","available":true},{"row":3,"position":"B","available":false},{"row":3,"position":"C","available":false},{"row":3,"position":"D","available":false}]

To highlight the available photos in the HTML, I need to parse this JSON and add a class of "photo-available" if the "available" property is true. Being new to Angular, I'm unsure about how to achieve this easily. Any guidance on what methods or directives to use would be appreciated.

Edit: The Angular code snippet for reference:

<ul class="table-rows">
    <li class="photo-row" ng:repeat="photo in photos" ng:class="'photo-' + photo.row + photo.position">
        <ul class="table-photos">
            <li class="photo photo-available" ng:class="selectedOrNot(photo)" ng:init="photo.selected = false" ng:click="photo.selected = !photo.selected">

         <div class="photo-number">{{photo.row + photo.position}}</div>                          
        </li>                                   
     </ul>                                
  </li>
  <div class="clear"></div>                          

Answer №1

Latest Update
If you are facing difficulties in restoring previous selections, it might be due to the fact that you are overwriting the selected property of the photo using ng-init:

ng:init="photo.selected = false"
ng-class="{'selected': photo.selected, 'available': photo.available}"

By setting photo.selected to false with ng-init, the 'selected' class will not be applied because of this hardcoded value. Simply removing ng-init should allow ng-class to function correctly and add the appropriate class for previous selections.

You can see a functional demonstration here: http://plnkr.co/tVdhRilaFfcn55h6mogu

Initial Solution
In case your list of photos is different from the available photos array, you can utilize a custom directive to apply the necessary class.

app.directive('availablePhoto', function($filter) {
  return {
    restrict: 'A',
    scope: true,
    link: function(scope, element, attr) {
      var id = attr.id

      var regex = /photo-(.)(.)/g;
      var match = regex.exec(id);

      var row = match[1]
      var position = match[2]

      var photo = $filter('filter')(scope.photos, {row:row, position:position}, false)

      console.log(photo);

      if (photo[0].available) {
        element.addClass('available');
      }
    }
  }
});

To implement this directive, simply attach it to each list item as shown below:

<li class="photo" id="photo-1A" available-photo>1A</li>

For a live demo, check out: http://plnkr.co/WJCmLf2M39fcUnvOPyNA

Recent Updates

After reviewing your latest update, it appears that there is only one array populating both the list and the availability status. Therefore, utilizing ngClass directly without a custom directive should suffice. Here's how you can integrate it into your code snippet:

<ul class="table-rows">
  <li class="photo-row" ng:repeat="photo in photos" ng:class="'photo-' + photo.row + photo.position">
    <ul class="table-photos">
      <li class="photo" ng-class="{'available': photo.available}" ng:init="photo.selected = false" ng:click="photo.selected = !photo.selected">
        <div class="photo-number">{{photo.row + photo.position}}
        </div>                          
      </li>                                   
    </ul>
  </li>
  <div class="clear"></div>  
</ul>

The plunker has been updated to showcase this functionality.
http://plnkr.co/WJCmLf2M39fcUnvOPyNA

Additional Update
To handle multiple classes with ngClass, use the following syntax:

ng-class="{'selected': photo.selected, 'available': photo.available}"

See an illustration combining selected and available classes here: http://plnkr.co/WJCmLf2M39fcUnvOPyNA

Answer №3

Here is a solution that should fit all of your criteria:

$scope.images = JSON.parse('[{"row":1,"position":"A","available":true},{"row":1,"position":"B","available":false}, ... {"row":3,"position":"D","available":false}]');

You can then utilize ng-repeat to generate the list:

<ul>
   <li class="row">
      <ul>
        <li ng-repeat="image in images" class="photo" ng-class="{'photo-available': image.available}" id="image-{{image.row}}{{image.position}}">{{image.row}}{{image.position}}</li>
      </ul>
   </li>
</ul>

This code loops through the image array and assigns each element to the variable image. If image.available is true, it adds the class photo-available to that item.

The ID and text for each item are generated based on their row and position properties ({{image.row}}{{image.position}}). You could also concatenate them with a plus sign like this: {{image.row + image.position}}, but be cautious if they are both numerical values.

http://plnkr.co/edit/abc123xyz987

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

Complete API Integration with Diverse Models for Android Development

Having trouble grasping some concepts about Rest API's. I successfully created 2 apps using JSON and POJO, where I had a large JSON file that allowed me to utilize Retrofit and move forward with the app. However, today I face a new challenge. I am tr ...

The ng-route feature seems to be malfunctioning and I am unable to identify the error, as no information is being displayed in the console

Here is the code in my boot.php file where I have set up the links <ul class="nav nav-pills nav-stacked"> <li role="presentation"><a href="#/valley">Valley</a></li> <li role="presentation"><a href="#/beach"> ...

Encountering a "Raphael is undefined" error message when working with Treant.js

I need help creating an organizational flow chart using treant.js. Below is my code snippet, but I'm encountering a 'Raphael is not defined' error that I can't seem to solve. Can someone please assist me with identifying the root cause ...

Executing multiple nested `getJSON` requests in a synchronous manner using jQuery

I am facing an issue with my code that connects to an API using $.getJSON. It retrieves JSON data and then iterates three times through a for loop because the data has 3 objects. During each of these iterations, it makes another $.getJSON call to fetch spe ...

Guide on implementing a date selector for each button/option clicked using Vue.js

My experience with Vuejs is still fresh, and I've incorporated 3 buttons named chart1, chart2, and chart3. Whenever any of these buttons are clicked, I want a Date selection to appear in a radio type format. You can see an example below: https://i.ss ...

The error encountered is: "TypeError: req.flash does not exist as a function in NodeJs

When it comes to working with Registration on a Site, the Validation process is key. In this case, mongoose models are being used for validation and an attempt is being made to utilize Flash to showcase error messages within the Form. However, there seems ...

Ensuring the correctness of phone numbers by validating them with country codes through the use of

I'm currently working on validating phone numbers using intl-tel-input, following the example provided at Below is the code snippet I've been using: var telInput = $("#phone"), errorMsg = $("#error-msg"), validMsg = $("#valid-msg"); // initial ...

Transferring binary data from C# to Node.js for deserialization

I am facing a challenge where I have a byte array created in C# from an object type, which is then sent over the socket protocol to a Node.js app. However, I am unable to deserialize the data into a readable object. Can anyone suggest a way to decode this ...

Invoke the URL with a query string and obtain the response from the specified web page

How can I make a button on my user.php page call action.php?name=john&id=10 without refreshing the page? The action.php page needs to process the query string data (name=john & id=10), execute some action, and then send a message back. Here is an ...

Retrieve the Javascript variable and assign it to a PHP variable

When attempting to assign a JavaScript variable to a PHP variable and output the value in an alert, I am encountering an error. The output is shown as "; alert(simple); var p1sds = "My Custom String"; <?php $dsfd = "<script>document.writeln(p ...

When executed on the node REPL, lodash.sortBy will update the lodash value

When I access the node REPL, the following happens: > _ = require('lodash'); > // it displays the whole lodash object > _.sortBy(['1234', '123'], function (element) { return element.length; }); > [ '123&apos ...

Adding to a JSON file in PHP: A step-by-step guide

My task involves generating JSON files to load into data tables, containing thousands of rows from the database. However, I am facing an issue where I receive a fatal error due to memory exhaustion while trying to allocate space for adding new rows. Fat ...

When attempting to input data into the database, an error is displayed stating that /test.php cannot be POSTed

Every time I try to input data using PHP, it throws an error Cannot POST /test.php. I've been attempting to fix it with no success. Can anyone please help me solve this issue? It's crucial for my project work. Here is my HTML code: <html> ...

How can I change the background color of a parent div when hovering over a child element using JavaScript

I am working on a task that involves three colored boxes within a div, each with a different color. The goal is to change the background-color of the parent div to match the color of the box being hovered over. CSS: .t1_colors { float: left; wid ...

Optimal Method for Organizing Items in Express.js Using Mongodb

Can you share your insights on the best practices for sorting objects in expressjs + mongodb(mongoose) web applications? Imagine we have a Product model with four attributes: var ProductSchema = new mongoose.Schema({ name: String, // "Summer T-sh ...

It is not possible to transfer information to a JSON document using node.js filesystem and browserify

In an attempt to convert incoming input data from a form into JSON format for storage without a backend, I am exploring the use of Node.JS module "fs" or "file-system". To make this work in a browser environment, I am using Browserify for bundling as it r ...

Exploring the world of routing parameters in Express.js and AngularJS

Struggling to configure routes with parameters in an AngularJS application supported by a node.js server running on express. The setup involves Node routing all unspecified paths to a catch-all function: app.use(express.bodyParser()); app.use(app.router); ...

ng-include once the application has finished loading

Currently, my server is using handlebars to generate the initial HTML page. I would like to include a ng-include in this page to dynamically update the client side. However, every time my application runs, it loads the page and the data-ng-include="templa ...

Is there a way to render a component without having to render AppComponent constantly?

I am looking to display two components (AppComponent and UserComponent) without constantly displaying AppComponent. Here's how my code is structured: app.routing.module.ts const routes: Routes = [ { path: '', component: AppComponent ...

Exploring the benefits of utilizing express-session for authentication management

I am currently in the process of creating a basic login application using express 4 and express-session. When setting up my code as follows: app.use(session({ store: new MongoStore({ db: 'sess' }), secret: 'Ninja Turtle', cookie ...