Issues encountered when attempting to use a unique filter method in AngularJS within an "ng-repeat" loop

Snippet of Code

//controller

$scope.filterByCategory = function (wine) {
  return $scope.filter[wine.search_by_item] || noFilter($scope.filter);
};


$scope.filterByLocations = function (w) {
    var chambers_location = [];
    for(var i=0; i<w.chambers.length; i++) {
      chambers_location = w.chambers[i].chamber_location_name;
    }
    return $scope.filter[chambers_location] || noFilter($scope.filter);
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<!-- filter with checkbox options -->

<h3 class="panel-title">Location</h3>

<ul>
    <div ng-repeat="cat in getCategories()">

        <label>
            <b> <input type="checkbox" class="doctor_checkbox" ng-model="filter[cat]"/> <span ng-if="cat!=0"><% cat %></span><span ng-if="cat==0">Others</span></b>
            <span >(<% (names | filter:cat).length %>) </span>

        </label>

    </div>

</ul>

<h3 class="panel-title">Areas</h3>
<ul>
    <div ng-repeat="locations in getLocations()">
        <label>
            <b> <input type="checkbox" class="doctor_checkbox" ng-model="locations" ng-if="locations!=null"/> <span ng-if="locations!=null"><% locations %></span></b>
            <span ng-if="locations!=null">(<%(names | filter:locations).length%>) </span>

        </label>
    </div>

</ul>
      
      
<!-- ng-repeat with filtered value -->

<div class="content-area-article content-area" ng-if="w.check_subscription == 1" ng-repeat="w in filtered=(names| filter:filterByCategory | filter:filterByLocations)">
  
  <!-- codes will go here -->
  
  
</div>

Issue with filterByCategory() and filterByLocations(): The two methods are not functioning properly when called within the same ng-repeat. However, individually, they work perfectly when one of them is commented out from the controller.

Seeking guidance on resolving this problem effectively.

Answer №1

The correct structure for your ng-repeat filters should be as follows:

ng-repeat="w in filtered | filter: filterByCategory | filter: filterByLocations"

Answer №2

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

            myApp.controller('myCtrl', ['$scope', function($scope){
                $scope.filterData = '';
                $scope.data = [{id: 1, fname: 'john'},

                    {id: 2, fname: 'alex'},
                    {id: 3, fname: 'mike'}
                ];

                $scope.myFunction = function(){

                    return $scope.data.filter(function(item){ 
                        return (item.id.toString().indexOf($scope.filterData) > -1 || item.fname.indexOf($scope.filterData) > -1)
                    }); //end of filter
                }; //end of myFunction 
            }])



      
    <!DOCTYPE html>
    <html ng-app="myApp">
    <head> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    </head>
    <body>

        <div ng-controller="myCtrl" >
            <span></span>
            <table  >
                <tr>
                    <td >filter by Id/  Name</td>
                    <td ><input type="text" ng-model="filterData" /></td>
                </tr>
                <tr>
                    <th> Id</th>
                    <th> Name</th>
                    
                </tr>
                <tr ng-repeat="obj in myFunction()">
                    <td>{{obj.id}}</td>
                    <td>{{obj.fname}}</td>               
                </tr>
            </table>
        </div></body>
    </html>

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

Unwrapping React: Mastering the Art of Prop Extraction and Sharing

Imagine I have 2 input elements below, both with the same props except for the className <ReactCardFlip> <input type="text" maxLength={1} className={inputStyles.input} defaultValue={value} ...

Ways to modify font color in JavaScript "type"

Recently, I came across a fascinating technique where by simply refreshing the page, the text changes sentences. I managed to implement the code successfully, however, I am having trouble changing the color, size, and alignment of the text. <script type ...

IE11 Error: Script1003 expected but not found

I'm in the process of adding IE11 support, but encountering the following errors: SCRIPT1003: Expected ':' File: vendor.bundle.js, Line: 8699, Column: 8 SCRIPT5009: 'webpackJsonp' is undefined File: app.bundle.js, Line: 1, Colum ...

The debate: Switching off Next.js SSG - Harness or Constant?

Currently experimenting with different methods to disable NextJS SSG. The following custom hook implementation is functional: import { useState, useEffect } from "react"; const useClientCheck = () => { const [isClient, isClient ...

What could be causing the error "SyntaxError: Expected token ']' to appear" to pop up?

Recently, I have been working on implementing a 'night mode' feature for a website. However, every time I attempt to execute the script, an error message pops up: "SyntaxError: Expected token ']'" on line 9. The problematic line in ...

Dynamic stylesheet in Vue component

Currently, I am utilizing a Vue component (cli .vue) and facing the challenge of selectively displaying my stylesheet based on a boolean value. To put it simply: When myVar==false, the component should not load its styles. <style v-if="myVar" lang="sc ...

Utilizing replace and regex in jQuery to add a space before a capitalized character within a word

these are the elements in the array WorkNumber WorkType Version Status Module Priority AssignedBy AssignedTo Subject Details EstimatedTime ActualTime CreatedDate ModifiedDate i would like the ou ...

Error encountered when attempting to use the .save() method on a [mongoose_model_object] - the function contact.save is

In this scenario, the middleware 'auth' is responsible for generating a JWT and authorizing the user. I have also created a Mongoose model called Contact. However, when attempting to execute contact.save(), I encounter an exception stating that c ...

Extracting data from websites using Node.js

Currently, I am tackling a task involving web scraping. To give you some context, I take the URL from my webpage and extract the content located between the <body> tags. My objective is to then display this extracted content on my website. Through my ...

Next.js Error: The text displayed on the page differs from the HTML rendered by the server

Currently, I am facing an issue with the error "Error: Text content does not match server-rendered HTML." Here is my scenario - I have received a dateTime from an API, for example '2022-12-25T11:22:37.000Z', and I want to display it on a compone ...

How can you access the name of an array form using event.target?

I have a few checkboxes with the name checkBoxName[]. How can I retrieve the values from them? I am trying to submit them using Fetch in my handleSubmit function but encountering issues. <div> <input type='checkbox' name='ch ...

Place an element in the middle of the svg

I have a D3.js svg element measuring (1000,1000) with a circle positioned randomly, such as (100,200). My goal is to adjust the svg so that the circle is centered at (500,500). I want to create a function that can do this for any randomly positioned circl ...

Adjust the value before moving to the next tab, or if you choose to leave the

Looking for help to display a popup message when a user edits any value? Check out this resource that I found. It currently only triggers when moving to another page, but I need it to work within an Ajax tab system as well. Here is the code I have tried: ...

If the window width is less than the specified value, hide the DIV and replace it with a

I came across a discussion about hiding a div if the screen is narrower than 1024px, and I'm looking to implement something similar based on the quoted code below. Essentially, I want to hide one div (id="krug_wide") if the window width is less than 1 ...

Check if a Discord.js bot responds based on whether a user holds a designated role

I'm looking to make my bot respond to a specific role. If the user does not have that role, I want the bot to reply with a message saying "You are not allowed to perform this command." Here is the code snippet I am using: client.on("message", (message ...

The @Mui datepicker seems to be causing some trouble with the react-hooks-form integration

Below is a code snippet where I showcase working and non-working sections (commented out). <Controller control={control} name="DOB" render={({ field }) => ( <LocalizationProvider dateAdapter={AdapterDayjs}> <DatePic ...

Tips for sending a unique button ID to a jQuery click function

Within a table row of a dynamically generated table, I have multiple buttons each with its own functionality. My goal is to figure out how to pass the specific button ID to the onclick event of that table row when one of these buttons is clicked. $(&apos ...

AngularJS: Recommendations for structuring code to dynamically update the DOM in response to AJAX requests

Within Angular's documentation, there is a straightforward example provided on their website: function PhoneListCtrl($scope, $http) { $http.get('phones/phones.json').success(function(data) { $scope.phones = data; }); $scope.order ...

Creating a schedule by aligning each day of the week with its corresponding date

weekly calendar<----img here--! I am looking to enhance my weekly table by incorporating a calendar system into it. Instead of just displaying the year in the image, I want it to showcase a 7-day week layout (for example: 12/20/20 - 12/27/2020), with ...

Modifying an item within an array of Mongoose models

I am working with a model schema that looks like this: { _id: foo cart: { items: [ { id: number name: string, } ] } } My goal is to locate the document by its id and then modify the name value of the object in ...