Implementing a dynamic table filter for every column using AngularJS

I have been working on a project to create a custom directive that generates a table with dynamic data and allows for sorting of columns. While the sorting function works as intended, I now want to implement filtering on all columns without specifying a specific field at runtime. The issue I've identified is with the use of

ng-repeat="row in customers|filter:{$scope.searchkey:$scope.search}"
. The problem seems to be that $scope is not returning an object as expected.

Below is the code snippet:

Index.html

<body>
<div> 
    <my-table input="Customers"></my-table>
    <br />
    <br />
    <br />
    <my-table input="Users"></my-table>
</div>
</body>

script.js

angular.module('DirectiveDemo', [])
  .controller('Controller', ['$scope', function ($scope) {
      $scope.Customers = [{ Name: "2Touqeer", Code: "2" },
                              { Name: "3Nadeem", Code: "3" },
                               { Name: "1Talha", Code: "1" },
                               { Name: "4Muslim Khan", Code: "4" }

      ];
      $scope.Users = [{ Name: "Touqeer", Code: "2", ID: "2Touqeer", CID: "CID1" },
                            { Name: "Nadeem", Code: "3", ID: "3Muslim", CID: "CID3" },
                             { Name: "Talha", Code: "1", ID: "1Nadeem", CID: "CID2" },
                             { Name: "Muslim Khan", Code: "4", ID: "1Talha", CID: "CID5" },
      { Name: "Khan", Code: "4", ID: "1Khan", CID: "CID78" }
      ];

  }])
  .directive('myTable', function () {
      return {
          restrict: 'E',
          transclude: true,
          scope: {
              customerInfo: '=input'
          },
          templateUrl: 'my-table-info.html',
          controller: function ($scope) {

              $scope.searchKey = 'CID';
              alert($scope.searchKey)
              $scope.reverseSort = false;
              $scope.search = '';
              $scope.List = [];
              $scope.order = function (item) {
                  $scope.orderByField = item;
                  alert($scope.search)
              }

              $scope.filterValue = function (itemKey,valueKey) {
                  $scope.searchKey = itemKey;
                  if (valueKey != 'undefined') {

                      $scope.search = valueKey;
                      alert($scope.search)
                  }


              }

          }
      };
  })

my-table-info.html

<table ng-transclude>

    <thead class="GridHeaderItem ControlBorder">
    <tr>
        <th ng-repeat="(key, value) in customerInfo[0]">  <a href="#" ng-click="order(key); reverseSort = !reverseSort">
                   {{key}}
            <span  ng-show="orderByField==key">
                            <span ng-show="!reverseSort">
                                <i class="glyphicon-circle-arrow-up glyphicon"></i>
                            </span>
                            <span ng-show="reverseSort">
                                <i class="glyphicon-circle-arrow-down glyphicon"></i>
                            </span></span>
                </a></th>
    </tr>
        <tr class="ControlBorderRight ControlBorderTop ControlBorderBottom">
         <td class=" ControlBorderLeft ControlBorderBottom" ng-repeat="(key, value) in customerInfo[0]" >
             <input type="text"  style="width:100%;" ng-model="searchfilter"   ng-change="filterValue(key,searchfilter);"  />
             <!--ng-change="filter(key);"-->

         </td>
    </tr>
          </thead>
    <tr ng-repeat="row in customerInfo|filter:{co[row]:2}|orderBy:orderByField:reverseSort" class="ControlBorderRight ControlBorderTop ControlBorderBottom   ">

        <td ng-repeat="col in row" class=" ControlBorderBottom ControlBorderLeft Control LabelControl">{{col}}</td>
    </tr>
</table>

Answer №1

To optimize your code, consider creating a personalized filter method using the syntax

angular.module('myMod',[]).filter('myFilter',function(){ return function(input){...} })
. This will enhance functionality and keep your code clean. Don't forget to update your ng-repeat directive to incorporate your custom filter like so:
ng-repeat="row in customers | myFilter"
. The data from each 'row' object will be passed into the filter function as the 'input' parameter.

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

Tips for creating a filter that meets multiple conditions in HTML

Click here for image descriptionI have the following code where I am utilizing story owner and story state. ng-repeat="item in IterationStories | filter: {Story: {storyOwner: filterRequestor}} | filter: {Story: {state: filterKey}} " //works fine when ...

I am having trouble with getting the templateUrl to function properly

Recently diving into Angular, I am currently working with Angular-UI-Router in combination with ASP.NET MVC 4. app.config(['$urlRouterProvider', '$stateProvider', function ($urlRouterProvider, $stateProvider) { $urlRouterProvider.other ...

How to retrieve data obtained from parsing readline and fs in node.js beyond the scope of the callback function

This specific question diverges from the one mentioned with an existing answer. It pertains to a snippet of code taken from node.js documentation involving the use of fs and readfile, with a focus on detecting an end-of-file flag, which appears to be the r ...

Learn the step-by-step process of dynamically adding elements to a JavaScript object in JSON structure

We are attempting to dynamically generate a JSON object using a for loop. The intended result should resemble the following: posJSON = [ { "position": [msg[0].Longitude, msg[0].Latitude], "radius": 0.05, "color": [255, 255, 0, ...

Having trouble with fs.readFile in Node.JS on Ubuntu?

Currently, I am facing an issue when trying to read XML files. Strangely, the code works flawlessly on my personal computer running OS X. However, when I run the same code on a DigitalOcean Ubuntu 16 Server, it fails to produce any results. I am utilizing ...

Creating a global variable in Angular that can be accessed by multiple components is a useful technique

Is there a way to create a global boolean variable that can be used across multiple components without using a service? I also need to ensure that any changes made to the variable in one component are reflected in all other components. How can this be ac ...

Javascript encountering issues with recognizing 'self.function' within an onclick event

Recently, I have been working on enhancing a Javascript file that is part of a Twitter plugin. One of the key additions I made was implementing a filter function for this plugin. Here is a snippet of the script showcasing the relevant parts: ;(function ( ...

Error in executing a function within an asynchronous function sequence

Whenever a user logs in, I want to update their data in Firestore. However, the code I am using does not seem to work as expected. It fails to create a custom User object from the firebase.User. Can anyone help me understand why this is happening and how ...

Uploading files using Angular can result in a null HttpPostedFileBase

When working with Angular in conjunction with MVC, I am facing an issue where the HttpPostedFileBase is coming up as null when attempting to upload a file. This is how the HTML looks: <input type="file" data-ng-model="fileName" onchange="angular.eleme ...

Incorporating the Revolution Slider jQuery plugin within a Vue.js environment

Currently, my goal is to transform an html project into a vue application. The initial project utilizes a jquery plugin for Revolution slider by including them through script tags in the body of the html file and then initializing them: <script type= ...

I am encountering difficulties with generating images on canvas within an Angular environment

I am trying to crop a part of a video that is being played after the user clicks on it. However, I am encountering the following error: ERROR DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may no ...

Troubleshooting Firebase functions that end with socket hang up error ECONNRESET

For the past two years, my Firebase Function has been successfully retrieving data from an external service with soap, parsing it, and sending it back to an Android app client. However, recently it suddenly stopped working without any changes on my part, g ...

Angular for user authentication page

I've been busy working on the login page, and I've managed to create a login UI that meets the requirements. However, I'm facing some challenges when it comes to validating the username and password. Being new to Angular and Web API, I might ...

I am looking for a way to display or conceal text depending on the presence of an image

Could you please help me with this? I am looking for a solution where text is displayed only when there is content in the src attribute of an img tag. Essentially, I need JavaScript code that can identify if an attribute has content and then make a paragra ...

Traverse each child element sequentially using setTimeout or a delay function

Looking to dynamically apply a CSS filter to a list of divs with a delay between each iteration. Here are my attempted solutions: $(this).children().each(function() { $(this).delay(5000).css("-webkit-filter", "brightness(2)"); }); And this alternativ ...

There seems to be an issue with FastAPI not sending back cookies to the React

Why isn't FastAPI sending the cookie to my React frontend app? Take a look at my code snippet: @router.post("/login") def user_login(response: Response, username :str = Form(), password :str = Form(), db: Session = Depends(get_db)): use ...

Aborting HTTP POST requests in IE due to error code 0x2ee2

Currently, I am utilizing angularjs for file uploads to my API. The page features a multi-file select option where users can choose one or multiple files. Upon selection, the page initiates calls to the api and uploads each file individually using requests ...

What techniques can I implement to optimize the speed of this feature in JavaScript?

I have developed a feature that highlights any text within a <p> tag in red based on a user-specified keyword. The current implementation works well, but it is slow when dealing with over 1000 lines of <p>. Is there a faster way to achieve this ...

How can we rearrange the newly added row from onRowAdd in Material Table to be displayed at the beginning of the section?

Title. According to the documentation for material table, when using editable with onRowAdd, the new row is always added at the bottom of the section. Is there a way to have it appear at the top instead? Alternatively, how can I add an onClick effect so t ...

JavaScript popup is no more visible on the webpage

Recently, I implemented a pop-up on my website that used cookies to prevent it from appearing every time a user visited a page. However, after making this change, the pop-up stopped showing altogether. Despite my best efforts in testing, researching, and s ...