A guide to sorting a list in AngularJS based on a variable

Looking to accomplish a straightforward task here. I need to organize a dropdown menu in angular based on a specified parameter. Sounds simple, right?

Here's the data returned from a call to the dataservice:

"success" : true,
    "data" : {
        "this_status" : [{
                "DefNo" : "111*A",
                "Com" : "111",
}, {
                "DefNo" : "222*B",
                "Com" : "222",
}, {
                "DefNo" : "333*C",
                "Com" : "333",
}
];
        "this_info" : [{
                 "Req" : "MUST",
                 "DefCom" : "111",
}, {
                 "Req" : "NoMUST",
                 "DefCom" : "222"
}, {
                 "Req" : "MUST",
                 "DefCom" : "333"
}]}

The goal is to generate a list of "DefCom" values that also have a corresponding "MUST" value. I want to display "DefCom" numbers with a "Req" set as "MUST" in a dropdown menu. In this case, the dropdown should include 111 and 333.

In the controller, I trigger the function:

   $scope.getDefCom = function(){
        MyAPIservice.getDefCom().success(function(response){
            $scope.info = response.data.this_info;
            $scope.infoList = $scope.info;
        });
        }

This factory is used for the purpose:

angular.module('MyAPI.services', [])
  .factory('MyAPIservice', function($http) {
    var MyAPI = {};
    MyAPI.getDefCom = function () {
        return $http({
            method: 'GET',
            url: '/thisis/mylink/'
        });
    };

    return invoiceheaderAPI;
});

So far, this successfully lists the DefCom numbers in the dropdown. Now, the next step is to apply a filter.

In this example, $scope.require = MUST.

Within the template:

<option ng-repeat="option in DefComList" value="{{option.DefCom}}">{{option.DefCom}} </option>

Attempting to add a filter like this:

ng-repeat="option in DefComList | filter: {Req: $scope.require}"

Realized inserting a $scope variable into a filter might not work as intended after further research. Most advice suggests creating a custom filter instead. So, I wrote my own using angular.forEach. Here's the filter code:

 $scope.filterDefs = function($scope) {
        var clrreturn = false;
        angular.forEach($scope.info, function(value, key) {
            if (value.DefCom == $scope.require)
                clrreturn = true;

        });
        return clrreturn;
    };

However, the custom filter runs before receiving the results of $scope.info from the $scope.getDefCom function. This triggers an

Error: undefined is not an object (evaluating '$scope.info')
error before $scope.info is fully loaded. Seems like a promises issue, so I attempted implementing deferred promises without success. Simple task turned challenging, but I refuse to give up!

Answer №1

It seems like you may be overanalyzing the situation. If I understand correctly, all you need in your filter is:

ng-repeat="option in DefComList | filter: require : true"

Make sure to use 'true' for exact matching so that searching for 'MUST' doesn't also match 'noMUST'.

I created a quick fiddle for you to reference: https://jsfiddle.net/nqya24r4/

If you only want to search the Req property specifically, you can use an object instead of a string in the filter. Here's another fiddle demonstrating this: https://jsfiddle.net/t3bw5L5d/2/

I hope this explanation helps clarify things for you.

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

When creating a FlipCard, you may encounter the error message "The object may be null" while using the document.querySelector() method

Having trouble creating a flipcard on Next.js with tsx. The querySelector('.cardflipper') doesn't seem to locate the object and I keep getting this error: "Possibly the object is null". Does anyone know a solution to help my method recognize ...

Attempting to comprehend the reason behind the presence of additional parentheses at the conclusion of a function invocation

Just a quick question I have while experimenting with an example involving OAuth. I want to make sure I fully understand what's going on before incorporating it into my own code. The example uses node, express, and passport-azure-ad. In the code sni ...

The modal form vanishes without any action when the form is clicked outside

Everything was working fine with the form submission until I turned it into a modal using Bootstrap. Now, when the form is rendered in the modal, users can tab and type without any issues. However, if they click on any element within the modal (including t ...

What is the best way to display a message or alert after a page has been re

I've implemented Jquery Toastr to display success messages, functioning similarly to an alert for a brief period. My objective is to display a message after the page reloads. The issue arises when the page is reloaded, causing the JavaScript to reloa ...

The issue with jqTransform not displaying the select box value on a hidden contact form

Could really use some assistance here and apologize if it's a hassle: Link to contact form To view the contact form, simply click the "Contact" button in the top left corner. The jqTransform jQuery plugin is being used to style it. Initially, it&apo ...

Utilizing D3.js to filter nodes and links by making multiple selections from a checkbox

I am interested in enhancing my current forced directed graph by adding more flexibility. You can access the Jsfiddle here. Currently, there are radio buttons that control the opacity of nodes and links. There are 4 types of nodes: Agent, Customer, Pho ...

Adjusting the background color of <tr> depending on the number of <tr> elements in the HTML using CSS

When working on my HTML page, I have utilized multiple <tr> tags with different bgcolor values such as: <tr bgcolor="#000000"> <tr bgcolor="#E5F1CC"> <tr bgcolor="#D30A0A"> <tr bgcolor="#656766"> I am aiming to assign unique ...

Loading AngularJS modules

I am facing a challenge in getting modules to work properly on an application that I am currently developing. This is the main file main.js 'use strict'; angular.module('clientPortalPublic',[ 'ngCookies', 'ngR ...

Handling exceptions in the event that the backend URL resource cannot be accessed

I'm facing an issue with my Vue.js single file component where I am trying to catch exceptions when the URL requested by axios.post is unreachable. I have encapsulated the entire code in a try block, but for some reason, the alert in the catch block i ...

A guide on transferring a Vue component to a custom local library

After successfully creating components using template syntax (*vue files), I decided to move common components to a library. The component from the library (common/src/component/VButton): <template> <button ... </button> </templat ...

Organizing child directives within a main template

Currently, I am in the process of creating a new directive called "info-card". My vision is to utilize it in the following manner: <info-card theme="light"> <info-header> <h2>Hello World</h2> </info-header> ...

Aligning the ant design carousel in the center of the page

I adjusted the size of an Ant Design carousel and now I want to position the image in the center of my screen. This is how the current image looks: https://i.sstatic.net/TmfDb.png Here is what I have attempted: const contentStyle = { heigh ...

Utilize Object.keys and Object.values to transform a JSON object into a ChartJS representation

I have a unique JSON file structure that I am trying to display in ChartJS. The data looks like this: { "AAPL": [ { "Q1": -26986, "Q2": -168099, "Q3": -137101, "Q4": -5 ...

Is there any python module available that can securely interpret obscured javascript strings?

Is there a way to safely de-obfuscate JavaScript strings in Python, particularly when the JavaScript code may be malicious? Are there any existing libraries that can assist with this task? I initially attempted to create my own solution for this problem, ...

What is the process of integrating an HTML web component with an HTML file? Can I use innerHTML = foo("myfile.html") to achieve

Using HTML web components allows me to define their code using this method: this.innerHTML = `<h1></h1>`; However, I find it cumbersome as I do not have access to the Emmet Abbreviation feature which slows down my component creation process. ...

Utilizing Vue components to streamline the process of adding and updating data

I have a rather straightforward parent/child component. I am looking to utilize the child component in two ways - first, for adding a new entry and second, for updating an entity. Here are the components that I've built: https://codepen.io/anon/pen/b ...

What is the best way to utilize node exec in synchronous mode?

I have a scenario where I need to run exec synchronously. Is there an alternative method to achieve this without using the deprecated execSync library? Can bluebird promises be used for this purpose? for (var i = 0; i < testCasesLength; i++) { va ...

Vue Service - 401 (Access Denied)

Whenever I attempt to execute the "getUserData" method, it results in a 401 (Unauthorized) error. Strangely enough, when I make a GET request to the URL "" with the same headers in Postman, it works perfectly fine! How can I properly set my request heade ...

Modify each combination of characters surrounded by two symbols within a string

How can I replace the string between two symbols in my Angular code? For example, how can I change "Hello "I am" software coordinator as "freelancer"" to "Hello {I am} software coordinator as {freelancer}" I have been trying to write the code for this, ...

Issue with setting ng-click scope in Angular JS when using ng-if

Recently, I encountered an issue with AngularJS: Attempting to set a scope value directly in an ng-click event does not work when the ng-click is within an ng-if statement that evaluates the same scope value. You can see an example here: http://jsfiddle.n ...