Using Angular to fetch a JSON list and apply filters

Hey there, I have a simple question about working with JSON files. Currently, I am retrieving a list of workers from a JSON file called workers.json.

[{
  “workarea”: [“office”, “transport”, “IT”],
  “picture”: “some url”,
  “name”: “Mark Janken”,
  “age”: 30,
  “location”: “Holland”
}]

In my Angular controller, I am successfully fetching this data like so:

myApp.controller('MainController', function($scope, $http) {

  $http.get('workers.json')
    .success(function(data){
    $scope.workers = data;
    });

});

Now, I'm wondering how I can implement client-side filtering, for example using a URL parameter like /get-workers?location=:location and potentially having multiple filters.

I'm not sure where to start with this, any help or recommended resources would be greatly appreciated. Thanks!

Answer №1

To implement this functionality on the client side, you'll need to integrate a router into your project.

Once you've added a router (I recommend using ui-router), you'll need to configure your states/routes like so:

$stateProvider
  .state('workers', {
     url: '/workers/:myFilter',
     ...
  })

In your controller, you can access this parameter using $stateParams with a simple line of code: $stateParams.myFilter

Here's an example of how your controller might look:

myApp.controller('MainController', 
  function($scope, $http, filterFilter) {

      $http.get('workers.json')
        .success(function(data){
           $scope.workers = data;
           $scope.filteredWorkers = 
             filterFilter($scope.workers, {
               location:$stateParams.myFilter
           });
        });

});

For more information, refer to the documentation. It's very user-friendly!

Answer №2

When the value is obtained from a server, it can be managed on the server side by using the query string to filter the data.

However, if you are retrieving the list from a JSON file, you will need to apply the filtering after obtaining the list.

myApp.controller('MainController', function($scope, $http, filterFilter) {

  $http.get('employees.json')
    .success(function(data){
       $scope.employees = data;
       $scope.filteredEmployees = filterFilter($scope.employees, {department:'finance'});
    });

});

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

How can I turn off autocomplete in MUI textfields?

Currently, I am working with the latest version of mui. Within my user contact info form, there is a zip code field that I do not want to be auto completed if the value is null. However, despite my efforts, it continues to autocomplete with the email saved ...

Error: The expected property name should be enclosed in double quotes at line 2, column 1

Currently, I am developing a ChatBot that is being trained on a month's worth of reddit comments. The script I am working on involves creating a database and loading it with data from a JSON file. Although the code successfully creates the sqlite3 DB ...

Utilizing Document AI to conduct seamless analysis on extensive volumes of information extracted from PDF documents

I am looking to enhance my app by adding a feature that allows users to extract text from image texts and convert them into usable data, such as in JSON format. This will enable better data research capabilities for my clients. The image-texts are large P ...

Secure access to an API using a certificate within a Vue.js application running on localhost

My vue.js app is built using vue-cli. The application is hosted at dev.example.com and the REST API can be found at dev.example.com/api/v1/. The backend has added an SSL certificate for security on the development environment. However, when I try to make a ...

Create a multidimensional array from an array of objects

I am trying to organize my data by creating an array and listing each material based on its status. Here is the structure of my current array: let data = [ { Name: 'House 1', Details:[ {Materials: ...

Data not being properly set in the form

Check out this chunk of HTML code: <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script> <script> function getCords(){ ...

What is the best way to invoke the datepicker function on all rows of table data that share the 'datepicker' class?

Hey there! I'm working with a table that features a JavaScript function for a datepicker, as well as the ability to add and delete rows. The challenge I'm facing is that each new row created has the same ID as the previous one. How can I ensure t ...

Guide on converting a JSON object to GSON in Java

Here is the API response returned in JSON format: {"id":1,"bps_id":"C199","summary":{"as_of_date":"2017-06-20","bp_earned":0,"bp_balance":"199400","bp_redeemed":"600"},"bps_message":{"eng":"mobile testing message","chi":"mobile testing message chi"},"bps_ ...

The onTableChange function in Mui-Datatable does not seem to be functioning properly when attempting to

Utilizing mui-datatable, I came across an official example on codesandbox where setState can be used on the tableState. You can check out the example here: https://codesandbox.io/s/trusting-jackson-k6t7ot?file=/examples/on-table-init/index.js handleTableIn ...

What is the best way to have two directives interact with each other?

As a beginner in angular js, I am curious if there is a way for two directives to interact with one another. I attempted to use require: "^mydirective" but strangely, it did not work as expected. ...

Return structured data through a node.js JSON API

I'm currently working on developing an API using Node.Js and MySQL, and I'm faced with the challenge of organizing the data returned by the API. When creating a new record through a POST request, the data submitted looks like this: { "S ...

What steps should I take to prompt Postman to interact with a Web API?

I have recently installed the Postman plugin for Chrome and I am curious about how to use it to call my web API. Currently, I am making an AJAX call in JavaScript with the following code: alert("Getting security token"); // Do AJAX call to get security t ...

Incorporating JSON Data into an Android App

I am facing a situation where I have a JSON file containing contacts that need to be transformed into objects for display in a ListView. However, I am struggling with accessing the contacts.json file. I am unsure of the correct location for this file so th ...

I have already added the ID, yet I am unable to set the property 'onclick' of null

I've encountered an issue even after adding an id in HTML for JS. Upon opening the website, I see the following error: Uncaught TypeError: Cannot set property 'onclick' of null Your assistance is greatly appreciated. <!DOCTYPE html&g ...

Looking to enhance code by using jQuery to substitute numerous href elements. Only seeking enhancements in code quality

I am currently using regular JavaScript to change the href of 3 a-tags, but I want to switch to jQuery for this task. var catNav = $('ul.nav'), newLink = ['new1/','new2','nwe3/']; catNav.attr('id','n ...

Sending a picture through AJAX using the camera feature of p5.js

Currently, I am exploring the camera functionality of p5.js to capture video. However, I am facing a challenge when trying to upload these images to a server using ajax. I am unsure about how to convert a p5.js Image object into a suitable format for trans ...

Converting a Postgresql row into a JSON array of values without keys

I am currently working on converting query results to JSON in PostgreSQL. My current query looks like this: select row_to_json(t) from (select * from mytable) t; For instance, if 'mytable' has three columns and three records, the output would ...

Chosen option within the AntD Select component

Using the AntD select component, there seems to be an issue where it displays "id" instead of "name" when selecting options. Is there a solution available for this problem? const MyComponent = () => { const data = [ { id: "5c83c2d ...

What is the best way to invoke a function that is defined in another controller?

One thing that stands out to me about jQuery is its ability for me to write a function and access it from anywhere in my application. However, I have noticed that AngularJS operates differently, which can be frustrating at times. For instance, consider the ...

What is the best way to extract information from a JSON array and showcase it in a TextView?

After referencing the coding example provided in this link, I have implemented the following code: public class food extends ListActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ...