Utilizing Angular Filters to Assign Values to an Object within a Controller

I have a JSON example with multiple records, assuming that each name is unique. I am looking to filter out an object by name in the controller to avoid constant iteration through all the records using ng-repeat in my HTML.

{
"records": [
  {
    "Name" : "Alfreds Futterkiste",
    "City" : "Berlin",
    "Country" : "Germany"
  },
  {
    "Name" : "Berglunds snabbköp",
    "City" : "Luleå",
    "Country" : "Sweden"
  },
  {
    "Name" : "Centro comercial Moctezuma",
    "City" : "México D.F.",
    "Country" : "Mexico"
  }
]
}

Ideally, I want to use the filtered object within my HTML like this:

<p> {{ filteredObj.Name}} </p>

In my controller, I am having issues applying the filter correctly and can't figure out why.

var myApp = angular.module('myApp', []);

myApp.controller('myCtrl', ['$scope', '$http', function($scope, $http) {
  $http.get('customers.json').success(function (data) {
    //I am struggling with the filter method here
    $scope.filteredObj = $filter('filter')(data.records, {name: "Alfreds Futterkiste");
  });
}]);

How should I correctly utilize the $filter function in the controller?

Answer №1

  1. Make sure to include $filter in your code.
  2. Remember that $filter returns an array, so be sure to select the first element and check if there are any results.
  3. Lastly, ensure that the second parameter in the filter function is written as Name, not name.

Here's how your final code should look:

myApp.controller('myCtrl', ['$scope', '$http','$filter', function ($scope, $http, $filter) {
  $http.get('customers.json').success(function (data) {
    // Check this part where I am filtering out the object I need
    $scope.filteredObj = $filter('filter')(data.records, { Name: "Alfreds Futterkiste" })[0];
  });
}]);

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

Dependencies for Grunt tasks

I am facing some issues with a grunt task named taskA that was installed via npm. The task has a dependency on grunt-contrib-stylus, which is specified in the package.json file of taskA and installed successfully. However, when I run grunt default from the ...

Is it illegal to escape quotes when using an image source attribute and onerror event in HTML: `<img src="x" onerror="alert("hello")" />`?

Experimenting with escape characters has been a fascinating experience for me. <img src="x" onerror=alert('hello'); /> <img src="x" onerror="alert(\"hello\")" /> The second code snippet triggers an illegal character error ...

When the button is clicked, I desire to reveal the background color of a specific div

<div class="mat-list-item" *ngIf="authService.isAdmin()" (click)="openModal('site-settings', site.siteID)"> <span class="mat-list-item-content">{{ "Application.site_settings_label&q ...

Arranging array elements by both date and alphabetical order using Javascript

Is there a way to sort the data by both date and alphabet at the same time? Alphabetical order seems fine, but the date sorting isn't working correctly. Thank you for any solutions. Data structure : [{ productId: 21, title: "Huawei P40 L ...

Is there a way to establish a condition for an onSubmit event?

I have a form that I'm working on, and I would like for an error message to pop up upon the first onSubmit, and then function normally on subsequent submissions. Here is the current setup: const [submitting, setSubmitting] = useState(false); const ha ...

What is the reasoning behind npm modules such as material-ui exporting both es6 and es5 files?

When installing several npm modules, such as @material-ui/core, I noticed that there are three different ways to import the same React component: import { AppBar } from '@material-ui/core' import AppBar from '@material-ui/core/AppBar/AppBar ...

How can I add scrolling functionality to the active list item with React?

I created a music player that allows users to search for songs by artist. Check out the CODE SANDBOX here! Take a look at how the SongsList component is structured in my project: const SongsList = (props) => { const { loading, errorMess ...

What is the best way to ensure that empty strings are not included in the length of my array?

I have encountered an issue with a JSON file that I fetch. The array syllables is capable of holding up to strings max. However, when I exclude 2 words, I end up with 2 words and 2 empty strings. Nevertheless, my front-end still expects 4 "strings". So, it ...

Creating a React component that initializes its state with an empty array

Currently, my component is designed to fetch data from an API and store a random selection of objects (currently set at 10) in an array called correctAnswerArray. To avoid selecting the same object more than once, I use the splice() method. After pushing t ...

Retrieve data from a JSON object and assign it to a variable in JavaScript

I'm currently working on implementing AJAX to send and receive data in Django. My model consists of three fields: id, parent, and text. However, when attempting to post the information back to Django, I encounter an error due to additional fields pre ...

The function array.push() is not achieving the intended outcome that I had in mind

Currently facing a rather frustrating issue. I'm attempting to utilize D3.js for dynamically plotting data (specifically, scores of individuals). Retrieving record data from a firebase database whenever changes occur - this is represented by an obje ...

What is the best way to assign a distinct identifier to every hyperlink within a specific class using jquery?

For a project I'm working on, I need to create a list of links and a save button. My goal is to hide the save button if a link has already been saved. To achieve this, I am thinking of assigning a unique ID to each link based on a specific number in t ...

How can I incorporate a second main app.js file in Node.js to improve the organization and cleanliness of my codebase?

Hello, I am currently using Node.js and the Express framework for my project. All of my server-side code is contained within my app.js file, which has become quite complex with almost 250 lines of code. Now, I need to add authentication functionality to my ...

Failed validation for Angular file upload

I attempted to create a file validator in the front end using Angular. The validator is quite straightforward. I added a function onFileChange(event) to the file input form to extract properties from the uploaded file. I then implemented a filter - only al ...

Preserve multiple selected values post form submission using PHP, HTML, and JavaScript

How can I retain the selected values in a form after it is submitted? My current code functions correctly when only one value is selected, but does not maintain all selected values when multiple are chosen simultaneously. Any assistance would be apprecia ...

Ways to verify if an array contains two identical object values?

I am in search of a way to determine whether my array contains duplicate object values or not. Let's say I have the following array of objects: const array = [ { id: "id1", quantity: 3, variation: "red", ...

Integrate Chrome extension using code

Is there a way to programmatically load a Chrome extension? Can it be done using web driver with external extension preferences, or perhaps through JavaScript or another scripting language? ...

The functionality of Angular Datepicker is disrupted when scrolling through the page

Coding in HTML <div class="col-5 col-md-3 px-0 daterange-picker"> <div class="form-group"> <div class="input-group"> <input type="text" id="second ...

stream a song with a font awesome symbol

Can an audio track be played using a font awesome icon, such as displaying the song name (mp3) with a play icon right next to it? When users click on the play icon, can the track start playing and be paused or stopped at will? The list will consist of app ...

Looking to showcase duplicate ranks that have been selected, and specifically identify which ranks are being duplicated using JavaScript/jQuery

In this section, we have implemented the logic to identify duplicate ranks. However, in addition to displaying which ranks are duplicated, I also aim to highlight the specific rank that is being duplicated within the range of 0 to 18. function validate( ...