Refresh ng-repeat array after implementing filter in controller

I am currently facing an issue with updating my table view when changing a variable that filters an array. The filter is applied in the controller based on the values of a specific variable called columnFilter. However, the filter does not reapply to update the table view once the variable changes.

JS

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


function MyCtrl($scope, $filter) {
    $scope.name = 'Superhero';
    $scope.col={name:""};
    $scope.TableData = [{
      name: "2017/03/01-14",
      specification: "1wk",
    },
    {
      name: "2017/03/01-17",
      specification: "Set-04",
    },
    {
      name: "2017/03/04-11",
      specification: "1wk",
    },
    {
      name: "2017/04/01-14",
      specification: "1wk",
    },
    {
      name: "2017/03/10-10",
      specification: "Set-04",
    },
    {
      name: "2017/03/10-10",
      specification: "Set-04",
    }
    $scope.TableDataFiltered = $filter('filter')($scope.TableData, $scope.col);
}

HTML
<div ng-controller="MyCtrl">
<input type="text" ng-model="col.name">
<table>
<thead>
  <tr>
    <th>name</th>
    <th>spec</th>
  </tr>
</thead>
<tbody>
  <tr ng-repeat="item in TableDataFiltered">
    <td>{{item.name}}</td>
    <td>{{item.specification}}</td>
  </tr>
</tbody>
</table>
</div>


For those suggesting the use of | filter: expression, I am aware of that option. However, the app has additional filters that require filtering in the controller itself. In this example, I provided a minimal demonstration which may not clearly convey that point.

Answer №1

Utilizing the filter in your HTML with Angular will enable dynamic re-evaluation of expressions when variables change. If you wish to call the filter directly from your code, follow a similar approach:

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


function MyCtrl($scope, filterFilter) {
    $scope.name = 'Superhero';
    $scope.col={name:""};
    $scope.TableData = [...];

    $scope.$watch('col', function(newCol) {
        $scope.TableDataFiltered = filterFilter($scope.TableData, newCol);
    });
}

It's worth noting that you can inject the desired filter directly without repeatedly looking it up in the filter provider. As mentioned in the documentation:

To do this, inject a dependency with the name <filterName>Filter into your controller/service/directive. For example, a filter named number is injected using the dependency numberFilter. The injected argument is a function that takes the value to format as the first argument, followed by filter parameters.

If you intend to use the filter within the controller, consider not exposing the unfiltered data in the $scope. In such cases, either treat it as a regular variable or move the table data outside the controller and into a service. This way, you can keep the controller focused on controlling tasks rather than handling data.

Answer №2

There is no requirement to explicitly declare $scope.TableDataFiltered in the controller, you can simply apply the filter directly in your template:


<tr ng-repeat="item in TableDataFiltered | filter : col.name">

Answer №3

No need to create a separate function for this task, you can simply utilize the inline syntax:

<tbody>
  <tr ng-repeat="item in TableDataFiltered | filter: col.name">
    <td>{{item.name}}</td>
    <td>{{item.specification}}</td>
  </tr>
</tbody>

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

What is the best way to handle exceptions when dealing with MongoDB?

Issue Encountering a problem where the try block fails to capture errors when utilized within the MongoClient's connect function in MongoDB. System Details Operating System: Linux (Mint, Tessa) Node.js Version: v10.16.0 (utilizing ES6 with nodem ...

Tips for validating user input within a specific range in React?

I need to restrict user input in an input field to a number range defined by minimum and maximum values. I am working on this functionality using React/Next js. <Input value={tripCoverage} onChange={(e) => { const value = e.target.v ...

Transform a checkbox input into two distinct buttons

I am trying to change the input checkbox that toggles between light and dark mode into two separate buttons. How can I achieve this functionality? Check out the demo here: https://jsfiddle.net/ot1ecnxz/1 Here is the HTML code: <input type="checkb ...

The alert message fails to appear during an Ajax request

I'm having trouble understanding why the Ajax function in this code snippet is not triggering the success or error functions: function get_cust_key(custid) { $.ajax({ type: "POST", url: 'http://localhost/Test/index.php/getCust ...

Each time the page is reloaded, an error message pops up: "TypeError: Cannot access attributes of an undefined object (referencing 'name')."

Everything seems to be working fine in my app, except for one issue when I try to refresh the page where an event is being edited (EditEvent Component). The error message I receive is: Uncaught TypeError: Cannot read properties of undefined (reading ' ...

Exploring Node troubleshooting with WebPack and Feathers

Currently, I am part of a team working on a project that involves using Node, Webpack, TypeScript, and Express/Feathers. While my fellow developers are experienced in these technologies, I have limited experience with JavaScript mainly on the client-side a ...

Pattern to identify a JSON string with Regular Expressions

Currently, I am working on developing a JSON validator from the ground up and have hit a roadblock when it comes to the string component. My original plan was to create a regex pattern that aligns with the sequence specified on JSON.org: Here is the regex ...

Tips for maintaining the current route in Vue.js after a page refresh while running the Vue.js project in development mode on a specific port?

In my router.ts file, I have defined two routes: export default new Router({ mode: "history", routes: [ { path: "/", component: require("./components/dashboard/Dashboard.vue")}, { path: "/counter", component: require("./components/ ...

When calling an API endpoint, nodeJS is unable to access the local path

I've encountered a strange issue with my code. When I run it as a standalone file, everything works perfectly fine. However, when I try to utilize it in my API endpoint and make a request using Postman, it doesn't seem to function properly. What ...

Exploring the potential of $scope within $timeout in AngularJS

I am attempting to display a default message on a textarea using AngularJS. Some of the values I want to include require the use of $timeout to retrieve the values. The message does not appear to show up with the following code: <textarea class="t ...

Substitute a JSONP API call using $.ajax() with a direct server-to-server API call

My javascript application utilizes an ajax function that has the following structure: $.ajax({ url: apiURL, dataType: 'jsonp', success: function(data) { if (data.ok) { //perform actions }}}); Everything was working perfectly until I ...

How can I restrict input to only numbers and one decimal point using JavaScript?

The following code I have is not functioning as expected: function validateInputValue(element) { var regex = /\D$/i; // Important: avoid white spaces in password if(regex.test(element.value)) { alert("Please check your input format"); e ...

What is the extent of a variable's visibility within an ng-repeat directive in AngularJS?

Can you tell me the scope of the showDetails variable? Does it only apply to its own li or does it impact all the li elements in the ul? For the full code, please visit http://jsfiddle.net/asmKj/ ul class="procedures" ng-app ng-controller="sample"> < ...

I am struggling to showcase the values of character names stored within an array

I am currently developing a Library Express App and utilizing fake data to easily showcase the values on the screen. const PopularBooks = [ { id: 1, title: "Harry Potter", characters: [ { id: 1, name: "Har ...

Using a variable name to retrieve the output in JavaScript

I created a unique JavaScript function. Here is the scenario: Please note that the code provided below is specific to my situation and is currently not functioning correctly. analyzeData('bill', 'userAge'); Function analyzeData(u, vari ...

Trigger a modal to open based on a specific condition

I have successfully implemented a default modal from Materialize, but now I am looking to add a conditional opening feature to it. In my application, there is a countdown timer and I want the modal to automatically appear when the countdown reaches a certa ...

Obtaining the local IP address of my system with React JS

Is there a way to retrieve the local IP of my computer within a React JS application? I would appreciate any suggestions on how to accomplish this. ...

Tips for automatically updating a MaterialUI DataGrid in a React JS application

Here's an overview of my current project: Users can save rows from deletion by clicking checkboxes (multiple rows at a time). Any unchecked records are deleted when the user hits the "purge records" button. I received some guidance on how to achieve ...

a solution to the focus/blur issue in Firefox's browser bug

I have created the following script to validate if a value entered in an input field already exists in the database. $('#nome_field').blur(function(){ var field_name=$('#nome_field').val(); $.ajax({ url: " ...

How can I activate the socket.io connection event in NodeJS?

I'm currently experimenting with socket.io on NodeJS and I am facing a challenge in figuring out how to activate the socket solely from NodeJS. Previously, I have been using socket.io by invoking it from the front end. However, I am curious if it is ...