What is the best approach to sorting nested JSON data in AngularJS?

Currently, I am faced with the challenge of filtering through a nested JSON array within AngularJS. The JSON structure I am dealing with is as follows:

articles_data: [{
    title: 'Bigfoot Afoot',
    tags: ['True stories', 'forests'],
    description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dapibus mi at nulla finibus pretium. Curabitur auctor lacus vitae varius viverra. Sed pharetra varius sapien, id hendrerit ipsum lacinia placerat. Morbi vitae neque ipsum. Curabitur sem neque, iaculis vel nisl a, condimentum commodo arcu. Morbi nec urna efficitur, tempor nisl a, aliquet felis. Ut non est massa. Proin eget purus est. Integer eu nisi sed nisi maximus sodales. Duis finibus turpis a velit consectetur, luctus eleifend metus scelerisque. Pellentesque suscipit iaculis purus vel convallis.",
    category: 'Bigfoot'
  },
  {
    title: 'Lockness Sighted!',
    tags: ['Sightings', 'Lakes'],
    description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dapibus mi at nulla finibus pretium. Curabitur auctor lacus vitae varius viverra. Sed pharetra varius sapien, id hendrerit ipsum lacinia placerat. Morbi vitae neque ipsum. Curabitur sem neque, iaculis vel nisl a, condimentum commodo arcu. Morbi nec urna efficitur, tempor nisl a, aliquet felis. Ut non est massa. Proin eget purus est. Integer eu nisi sed nisi maximus sodales. Duis finibus turpis a velit consectetur, luctus eleifend metus scelerisque. Pellentesque suscipit iaculis purus vel convallis.",
    category: 'Nessy'
  },
  {
    title: 'Jacktalopes Everywhere',
    tags: ['Rabbits', 'cities'],
    description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dapibus mi at nulla finibus pretium. Curabitur auctor lacus vitae varius viverra. Sed pharetra varius sapien, id hendrerit ipsum lacinia placerat. Morbi vitae neque ipsum. Curabitur sem neque, iaculis vel nisl a, condimentum commodo arcu. Morbi nec urna efficitur, tempor nisl a, aliquet felis. Ut non est massa. Proin eget purus est. Integer eu nisi sed nisi maximus sodales. Duis finibus turpis a velit consectetur, luctus eleifend metus scelerisque. Pellentesque suscipit iaculis purus vel convallis.",
    category: 'Jacktalope'
  }
]

My current approach involves utilizing an ng-repeat to iterate through the array:

<div class="col-md-7 articles">
  <section>
    <div class="card filter" ng-repeat="article in articles.articlemanager.articles track by $index">
      <div class="card-header">
        {{article.title}} &nbsp;<small>{{article.tags.join()}}</small>
        <span class="badge badge-{{article.category}} float-right">{{article.category}}</span>
      </div>
      <div class="card-body">
        <p>
          {{article.description}}
        </p>
      </div>
    </div>
  </section>
</div>

While this successfully displays the articles, I am now looking to enhance the functionality by implementing filters based on name or tags:

<form>
  <div class="form-group">
    <label for="filterName">Filter by name</label>
    <input type="text" class="form-control" id="filterName">
  </div>
  <div class="form-group">
    <label for="filterTags">Filter by tags</label>
    <input type="text" class="form-control" id="filterTags">
  </div>
</form>

Although I lack expertise in utilizing filters within AngularJS, I am under time constraints and would greatly appreciate any assistance or guidance. Thank you in advance.

Answer №1

Simply include the | filter after your ng-repeat and store it in a ng-model that is linked to an <input>. To apply additional filters, just append more using the pipe symbol |. For more information on filters, check out the documentation here.

var app = angular.module("DummyApp", []);

var DummyController = function($scope) {
  $scope.articles_data = [{
      title: 'Bigfoot Afoot',
      tags: ['True stories', 'forests'],
      description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dapibus mi at nulla finibus pretium. Curabitur auctor lacus vitae varius viverra. Sed pharetra varius sapien, id hendrerit ipsum lacinia placerat. Morbi vitae neque ipsum. Curabitur sem neque, iaculis vel nisl a, condimentum commodo arcu. Morbi nec urna efficitur, tempor nisl a, aliquet felis. Ut non est massa. Proin eget purus est. Integer eu nisi sed nisi maximus sodales. Duis finibus turpis a velit consectetur, luctus eleifend metus scelerisque. Pellentesque suscipit iaculis purus vel convallis.",
      category: 'Bigfoot'
    },
    {
      title: 'Lockness Sighted!',
      tags: ['Sightings', 'Lakes'],
      description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dapibus mi at nulla finibus pretium. Curabitur auctor lacus vitae varius viverra. Sed pharetra varius sapien, id hendrerit ipsum lacinia placerat. Morbi vitae neque ipsum. Curabitur sem neque, iaculis vel nisl a, condimentum commodo arcu. Morbi nec urna efficitur, tempor nisl a, aliquet felis. Ut non est massa. Proin eget purus est. Integer eu nisi sed nisi maximus sodales. Duis finibus turpis a velit consectetur, luctus eleifend metus scelerisque. Pellentesque suscipit iaculis purus vel convallis.",
      category: 'Nessy'
    },
    {
      title: 'Jacktalopes Everywhere',
      tags: ['Rabbits', 'cities'],
      description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dapibus mi at nulla finibus pretium. Curabitur auctor lacus vitae varius viverra. Sed pharetra varius sapien, id hendrerit ipsum lacinia placerat. Morbi vitae neque ipsum. Curabitur sem neque, iaculis vel nisl a, condimentum commodo arcu. Morbi nec urna efficitur, tempor nisl a, aliquet felis. Ut non est massa. Proin eget purus est. Integer eu nisi sed nisi maximus sodales. Duis finibus turpis a velit consectetur, luctus eleifend metus scelerisque. Pellentesque suscipit iaculis purus vel convallis.",
      category: 'Jacktalope'
    }
  ]
}

app.controller("DummyController", ["$scope", DummyController]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="DummyApp">
  <div ng-controller="DummyController">
    <form>
      <div class="form-group">
        <label for="filterName">Filter by name</label>
        <input type="text" class="form-control" id="filterName" ng-model="filterName">
      </div>
      <div class="form-group">
        <label for="filterTags">Filter by tags</label>
        <input type="text" class="form-control" id="filterTags" ng-model="filterTag">
      </div>
    </form>
    <div class="col-md-7 articles">
      <section>
        <div class="card filter" ng-repeat="article in articles_data | filter:filterName | filter:filterTag">
          <div class="card-header">
            {{article.title}} &nbsp;<small>{{article.tags.join()}}</small>
            <span class="badge badge-{{article.category}} float-right">{{article.category}}</span>
          </div>
          <div class="card-body">
            <p>
              {{article.description}}
            </p>
          </div>
        </div>
      </section>
    </div>
  </div>
</div>

Answer №2

If you're unsure about what you want, the simplest method to use with ng-repeat is the filter function.

<li ng-repeat="x in names | orderBy:'FirstName'">

For more information and various options available, refer to the AngularJS Documentation on the filter function.

Answer №3

<div class="box filter" ng-repeat="post in articles.articlemanager.articles | filter : filterTitle | filter: filterCategories track by $index">

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

The tool tip feature is not recognizing line breaks

I've encountered an issue with the tooltip in my project. Despite trying various solutions found on stackoverflow, I am still unable to resolve it. In my ReactJS application, I am dynamically creating elements using createElement and applying the too ...

We encountered an issue: Headers cannot be set after they have been sent while attempting to read files

I encountered an error when attempting to read a file and send the response back to the browser. [ 'Error: Can\'t set headers after they are sent.', ' at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)&apo ...

Processing incoming requests with a loading interface in CodeIgniter

Is there a way to notify the user who sent the request whether or not the requested user will approve it? Optional: If there is no notification sent to the user who made the request, the requested user will have to wait for verification. For Example: Ima ...

Looking to maintain the value of a toggle button in a specific state depending on certain condition checks

I have a situation where I need to keep a toggle button set to "off" if my collection object is empty. Previously, I was using v-model to update the value of the toggle button. However, now I am attempting to use :value and input events, but I am strugglin ...

Using ng-class directive with condition in AngularJS

Here is a unique pop-up that allows users to encode item information. https://i.sstatic.net/sn9QZ.png I need to implement a feature where, if both the Foreign Currency and Conversion Rate fields have values, the Amount should be calculated by multiplying ...

Tips on submitting a nested dataset and a collection of photos

There are two main models available: Product and Picture. Each instance of the Product model can have multiple Picture objects associated with it. I am seeking guidance on how to create a new Product using a POST request that includes nested objects contai ...

Is there a more efficient method for managing Express rendering based on whether the request is an AJAX post or an HTML form submission?

Currently, I am working on an HTML form and incorporating jQuery's AJAX post feature to retrieve information based on the success or failure of a database insertion. Within my code, I have set the ajax post variable to true when utilizing AJAX postin ...

Unspecified variable in AngularJS data binding with Onsen UI

I am new to Onsen UI and AngularJS, and I have a simple question about data binding. When I use the variable $scope.name with ng-model in an Onsen UI template, it returns as UNDEFINED. Here is my code: <!doctype html> <html lang="en" ng-app="simp ...

Replicate the functionality of a mouse scrolling event

I have incorporated Jack Moore's Wheelzoom jQuery plugin to zoom and drag an SVG image on my website. However, I also want to include manual zoom in and out buttons for the users. I am considering two options to achieve this - triggering a mouse whe ...

Navigating with React Router v6 beyond the confines of individual components

When using react-router v5, I would create the history object like this: import { createBrowserHistory } from "history"; export const history = createBrowserHistory(); Then I would pass it to the Router like so: import { Router, Switch, Route, Link } from ...

Generating clickable markers that trigger an AlertDialog to appear in real-time

I am currently working on dynamically adding markers to a map, pulling data from JSON. The marker addition process is functioning correctly, as I can successfully add multiple markers in various locations. However, when I click on a marker, I want an alert ...

Steps for setting a background image behind radio buttons

I am currently facing a challenge in adding a background image to a div that contains some radio buttons and updating it dynamically with Angular based on the current page. app.controller('thingCtrl', function ($scope, $rootScope, $routeParams ...

Is there a tool that can help pinpoint the original collection for shared elements across multiple collections?

When given multiple collections/arrays, I am interested in identifying the common elements and which collections they belong to. This request is somewhat similar to this query, but there may be matching elements between collection1 and collection3, or eve ...

Is it possible to disable the "super must be called before accessing this keyword" rule in babelify?

My current setup involves using babelify 7.2.0 with Gulp, but I've encountered an error when working with the following code snippet: class One {} class Two extends One { constructor() { this.name = 'John'; } } The issue at hand i ...

Establish a foreign key constraint on a JSON data type field

Recently, SQL Server introduced JSON support which opens up new possibilities. Check out this link for detailed information. We are considering utilizing this feature to store our translatable fields. Instead of having a separate table for translations in ...

Guide to retrieving data from a JSON API

I'm struggling with a JSON file named runs.json, and I want to use Ajax to make a call to it. However, the specific value I need from the JSON is repeatedly showing as undefined. Here's an example of the JSON structure: { "status": "true", ...

Alias destructuring for arrays within nested objects

I'm currently attempting to change the names of certain objects from one array (eventFetch) and transfer them into another array (mapEvents). I initially tried using destructuring aliases for this task, but since I need to rename a nested object, it d ...

The way jQuery and CSS are rendered in the same browser window can vary depending on whether they are loaded via Django or statically

Experiencing a perplexing dilemma. While viewing a web page created using html, jquery, and css on the same browser but in two separate tabs, I am encountering varying renderings of the page. Scenario 1: Directly loading the html file from the file system ...

Struggling with a TypeError in React/Next-js: Why is it saying "Cannot read properties of undefined" for 'id' when the object is clearly filled with data?

Encountering an issue with a checkbox list snippet in Next-js and React after moving it to the sandbox. Each time I click on a checkbox, I receive the error message: TypeError: Cannot read properties of undefined (reading 'id') This error is co ...

Encountering issues with ASP.NET WebAPI: When using $.ajax, a 404 error occurs, while using $.getJSON results in an Uncaught

Currently, I am developing an ASP.NET web API with a C# project that I am attempting to call from JavaScript. Below is the snippet of my JavaScript code: function LoadGraph() { var file = document.getElementById("file-datas"); if ('files' in fi ...