AngularJS retrieve data from JSON (like using MySQL)

My data is in JSON format:

{"sectionTitle":"Account Information","sectionItems":[{"itemTitle":"Balance","url":"/account/balance","selected":true},{"itemTitle":"Account Statement","url":"/account/statementsearch","selected":false},{"itemTitle":"Deposit","url":"/account/deposit","selected":false},{"itemTitle":"Withdrawal","url":"/account/withdraw","selected":false},{"itemTitle":"Edit Profile","url":"/account/editprofile","selected":false},{"itemTitle":"Change Password","url":"/account/changepassword","selected":false}]}

Is there a way to check if any child item within the sectionTitle has selected set to true?

Similar to this SQL query:

SELECT * FROM sectionItems WHERE selected=true

Can I achieve something similar using AngularJS to determine if the parent has children?

I hope my question makes sense.

This is the HTML snippet I'm working with:

           
<nav class="sidebar-nav">
    <ul class="nav metismenu" id="side-menu-help">

        <li ng-repeat="menuItem in accountCtrl.menuStructure">
            <a class="{{ (menuItem.sectionItems.length > 0) ? 'metisHasChildren' : '' }}" href="/en/help-area/poker-help/poker-rules/">
                <span ng-if="menuItem.sectionItems.length > 0" class="fa arrow fa fa-angle-double-down"></span>
                {{ ::menuItem.sectionTitle }}
                {{ ::menuItem }}
            </a>
            <ul class="nav nav-second-level collapse in">
                <li ng-repeat="subMenuItem in menuItem.sectionItems" ng-click="accountCtrl.changePage(subMenuItem.url)">
                    <a ng-class="(subMenuItem.selected) ? 'page-active' : ''">{{ ::subMenuItem.itemTitle }}</a>
                </li>
            </ul>
        </li>

    </ul>
</nav>

Answer №1

Getting this to work doesn't require any fancy tricks. Just convert the json into an object and then access the desired property using dot notation. Here's a simple example:

var jsonData      = JSON.parse(json);
var selectedItems = [];

angular.forEach(jsonData.sectionItems, function(item) {
    if (item.selected) {
        selectedItems.push(item);
    }
});

This code snippet will convert the json string into an object, loop through each child sectionItem, check if selected is true, and build an array of matching items.

Answer №2

If you're looking to filter out specific sectionItems based on a condition, consider using a forEach loop. In this example, we are creating an array of sectionItems where the 'selected' property is true, but feel free to adjust it as needed.

$scope.items =[];
angular.forEach(sectionItems, function(item){
  if (item.selected === true){
    $scope.items.push(item);
  }
})

UPDATE

For a demonstration, check out this functioning plunk

To integrate this filtering technique seamlessly with ng-repeat, utilize it within a custom filter like so:

app.filter('menuFilter', function() {

  return function(menuItems) {
    var filtered = [];

    angular.forEach(menuItems, function(menuItem) {
      angular.forEach(menuItem.sectionItems, function(item) {
        if (item.selected === true) {
          filtered.push(menuItem);
        }
      });
    });

    return filtered;
  }
});

Finally, update your markup in this way:

ng-repeat="menuItem in accountCtrl.menuStructure | menuFilter "

Answer №3

Start by utilizing the standard filter without the need for a custom filter:

<li ng-repeat="menuItem in accountCtrl.menuStructure | filter: { sectionItems: { selected: true } }"> {{ menuItem.sectionTitle }}

Demo of this implementation:

angular.module('app', [])
  .controller('accountController', function() {
    var vm = this;
  
    vm.menuStructure = [  
       {  
          "sectionTitle":"Account Information",
          "sectionItems":[  
             {  
                "itemTitle":"Balance",
                "url":"/account/balance",
                "selected":true
             },
             {  
                "itemTitle":"Account Statement",
                "url":"/account/statementsearch",
                "selected":false
             },
             {  
                "itemTitle":"Deposit",
                "url":"/account/deposit",
                "selected":false
             },
             {  
                "itemTitle":"Withdrawal",
                "url":"/account/withdraw",
                "selected":false
             },
             {  
                "itemTitle":"Edit Profile",
                "url":"/account/editprofile",
                "selected":false
             },
             {  
                "itemTitle":"Change Password",
                "url":"/account/changepassword",
                "selected":false
             }
          ]
       },
       {  
          "sectionTitle":"Account Information 2",
          "sectionItems":[  
             {  
                "itemTitle":"Balance",
                "url":"/account/balance",
                "selected":false
             },
             {  
                "itemTitle":"Account Statement",
                "url":"/account/statementsearch",
                "selected":false
             },
             {  
                "itemTitle":"Deposit",
                "url":"/account/deposit",
                "selected":false
             },
             {  
                "itemTitle":"Withdrawal",
                "url":"/account/withdraw",
                "selected":false
             },
             {  
                "itemTitle":"Edit Profile",
                "url":"/account/editprofile",
                "selected":false
             },
             {  
                "itemTitle":"Change Password",
                "url":"/account/changepassword",
                "selected":false
             }
          ]
       }
    ];
  });
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>

<body ng-controller="accountController as accountCtrl">
  <ul>
    <li ng-repeat="menuItem in accountCtrl.menuStructure | filter: { sectionItems: { selected: true } }"> {{ menuItem.sectionTitle }}
      <ul class="nav nav-second-level collapse in">
        <li ng-repeat="subMenuItem in menuItem.sectionItems" ng-click="accountCtrl.changePage(subMenuItem.url)">
          <a ng-class="{ 'page-active': subMenuItem.selected }" ng-bind="::subMenuItem.itemTitle"></a>
        </li>
      </ul>
    </li>
  </ul>
</body>

</html>

Suggestions:

  1. Instead of using ngClass with ternary operator, you can simply use this approach:
ng-class="{ 'page-active': subMenuItem.selected }"
  1. While your current method works fine, consider exploring the special-repeats feature which may be more suitable for your scenario.

I trust this information proves useful!

Answer №4

let data = [{"sectionTitle":"Account Information","sectionItems":[{"itemTitle":"Balance","url":"/account/balance","selected":true},{"itemTitle":"Account Statement","url":"/account/statementsearch","selected":false},{"itemTitle":"Deposit","url":"/account/deposit","selected":false},{"itemTitle":"Withdrawal","url":"/account/withdraw","selected":false},{"itemTitle":"Edit Profile","url":"/account/editprofile","selected":false},{"itemTitle":"Change Password","url":"/account/changepassword","selected":false}]}];
let selectedItems = data.filter(item => item.sectionItems.some(subItem => subItem.selected));

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

Creating a consistent base URL for both Vue and Apache reverse proxy configurations

Currently, I am experimenting with a Vue app and testing it using pm2 in conjunction with Apache. After starting the app with pm2 and running it on port 3000, I then utilize an Apache reverse proxy to access the app through a domain and HTTPS. However, I e ...

Verify if a fresh message has been added using AJAX

Is it possible to create a notification system similar to Facebook, where the tab title displays the number of new messages without refreshing the entire page? Below is a snippet of code from my website's message box feature that I am working on. < ...

Tips on how to update the page and create a counter for a table view

I am working with an HTMLB Tableview where I need to regularly update its firstRowVisible property every 3 minutes with a dynamic value. For example, if it starts at zero, after 3 minutes it should be set to 21 and continue increasing by a certain interval ...

How to retrieve properties of the final item in an array using Vue.js

Struggling with Vue.js JavaScript implementation. This is the current code: <div id="app"> <h1>Items</h1> <div v-for="item in items"> <input v-model="item.val"> </div> <button @click="addItem"> Ne ...

When scrolling the page, the Circle Mouse Follow feature will dynamically move with your cursor

Hey everyone! I'm currently working on implementing a mouse follow effect, but I'm facing an issue where the circle I've created moves along with the page when scrolling, instead of staying fixed to the mouse. Any suggestions or tips would b ...

Generating a primary XML element encompassing multiple namespaces

I am currently working on integrating Restful services with Backbone.js framework. In this project, I need to send XML data and add multiple namespaces to it. Here is the snippet of my current JavaScript code: var mainNamespace = "xmlns='http://serv ...

What is the mechanism behind jQuery triggering the execution of JavaScript code contained in script tags that are retrieved in an AJAX response?

What is the unique ability of jQuery that allows JavaScript code inside script tags in an AJAX response to be executed? In the absence of jQuery AJAX, using eval() has been a common method to achieve this functionality as discussed in posts such as: Cal ...

Implementing JSON Serializer Settings at a Global Scale in ASP.NET MVC

The navigation properties in Entity Framework are causing an exception of "Circular Object Reference" when the collection in my View Model is being serialized by Kendo Grid. Despite setting "ReferenceLoopHandling" to "Ignore" globally in my Application_Sta ...

Customize Button Colors in Bootstrap 4

I'm encountering difficulties when attempting to change the color of the buttons labeled "Print," "Excel," and "PDF". Despite referring to a guide, I wasn't able to succeed. The provided test case differs from my code but shares the same CSS and ...

What is the simplest way to transform a JSON containing strings into a JSON with arrays?

I am tasked with creating a method named public string PrepareForDeserialization(string json) that will transform a JSON string such as: {"To":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a2ccc3cfc7e2c1cdcfd2c3ccdb8cc1cdcf" ...

Leveraging sequelize for storing and fetching JSON data in a Model/Instance

I'm embarking on a major project and considering using sequelize to manage it. I want to store a JSON Object as a property in a Model, but seem to be struggling with the implementation. While defining my model (Context), I have encountered some diffi ...

When attempting to make a GET request from AngularJS to Phalcon using the $http method, the params array

I am currently using Angular 1.6.2 with Phalcon framework. $scope.selectAction = function(Item){ $http({ method: 'GET', url: 'Mycontroller/new', params : {Item : Item}, headers : {'Accept' : 'application/json&ap ...

The image slider script I've built is functioning perfectly in Codepen, but unfortunately, it's not working as

My image slider called Orbit is functioning properly on Codepen.io, however when I try to run the exact same code on Plunker, it doesn't work at all. <ul class="slider" data-orbit> <li> <img src="http://foundation.zurb.com/docs/a ...

`Is it common to use defined variables from `.env` files in Next.js applications?`

Next.js allows us to utilize environment variable files such as .env.development and .env.production for configuring the application. These files can be filled with necessary environment variables like: NEXT_PUBLIC_API_ENDPOINT="https://some.api.url/a ...

Why is my Typescript event preventDefault function ineffective?

Despite all my efforts, I am still unable to prevent the following a tag from refreshing the page every time it's clicked. <p> <a onClick={(e) => handleClick} href="&qu ...

Incorrect outcome when utilizing ajax to update a div within a for each loop

For a while now, I've been facing an issue with a div and form within a forEach loop. When one of the forms in the loop is submitted, the content inside the corresponding div is updated in the database and refreshed using JavaScript and Ajax. The upda ...

Learn how to extract information from a JSON data array and seamlessly integrate it into an ObservableCollection using C# in Xamarin

Reviewing my JSON data { "found": 501, "posts": [ { "ID": 2500, "site_ID": 1, "date": "2014-09-26T15:58:23-10:00", "modified": "2014-09-26T15:58:23-10:00", "title": "DOD HQ Visitors Parking", "metadata": [ { "id": "15064", "key": "city", ...

What is the method for retrieving information from a JSON file that has been uploaded?

I am working with some HTML code that looks like this: <input type="file" id="up" /> <input type="submit" id="btn" /> Additionally, I have a JSON file structured as follows: { "name": "Jo ...

Is it possible to import npm modules conditionally?

Here is the structure of my project: - workspace - customPackage - customIndex.js - myProject - index.js - myProject2 - index.js During development, I need to import the package from my local workspace like this: //index.js import some ...

Struggling to log the values emitted from socket.io and express-nodejs

Having an issue with socket.io where the code is not emitting a value on a specific route. It works fine on the '/' route, but once I click submit and the route changes to '/process_post', I am unable to catch the emitted values by sock ...