Utilizing scope parameters in conjunction with filters

I'm looking for a filtering solution to filter results displayed in a table using ngRepeat. The filter should be based on user input.

Currently, I'm implementing it like this:

//HTML
<input type="search" ng-model="search">

<table>
  <tr ng-repeat="person in clients | filter: searchFilter">
    <td><input type="text" ng-model="person.Vorname"></td>            
  </tr>
</table>

The controller / Filter function:

app.controller('MyCtrl',function($scope){
  $scope.searchFilter = function (obj) {
    var re = new RegExp($scope.search, 'i');
    return !$scope.search || re.test(obj.Vorname) || re.test(obj.Firma);
  };
});

Everything is functioning correctly. However, I'm unsure if this is the best approach.

Should I consider moving my filter function to an Angular filter for better standards compliance?

If so, how can I pass the value from my input element to the filter? Passing the scope itself seems too dependent on the scope. What would be the best practice in this case?

Looking for guidance on the most effective way to handle this filtering process.

Answer №1

Is it recommended to move my filter function to a proper angular.filter for better standards compliance?

Indeed, the preferred approach is to utilize filters as utilities (similar to singletons like service, provider, factory).

Filters do not rely on $scope; instead, they generate output based on input. Therefore, you can define your filter in the following manner:

app.filter('myfilter', function() {
   return function( items, types) {
    var filtered = [];

    angular.forEach(items, function(item) {
       // <some conditions>
          filtered.push(item);  // dummy usage, returns the same object         
        }
    });

    return filtered;
  };
});

Adapted from Fiddle Demo

For Reference

If you are using the codeigniter framework with angular seed, notice that they employ a separate file named:

filters.js      --> custom angular filters 

The project structure resembles:

app/                --> all files utilized in production
  css/              --> cascading style sheets
    app.css         --> default stylesheet
  img/              --> image files
  index.html        --> primary app layout template
  index-async.html  --> loads js files asynchronously from index.html
  js/               --> javascript files
    app.js          --> application logic
    controllers.js  --> application controllers
    directives.js   --> application directives
    filters.js      --> custom angular filters
    services.js     --> custom angular services
  lib/              --> angular and third-party JavaScript libraries
    angular/
      angular.js        --> latest version of AngularJS
      angular.min.js    --> minified AngularJS
      angular-*.js      --> various Angular add-on modules
      version.txt       --> version information
  partials/             --> Angular view partials (HTML templates)
    partial1.html
    partial2.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

Divide the array into distinct characters or verify the presence of a specific character

I have designed 3 buttons with unique names. When button A is clicked, it appends the value to an array. For example: <a href="#" class="answer" data-value="Football">Football</a> Clicking on this button will add "Football" to an empty array. ...

Guidelines for transforming an HTML string into a JavaScript document

Is there a simplified method to transform an HTML string into JavaScript code that generates the same markup using the DOM? Something similar to: Input <div class="foo" tabindex="4"> bar <button title="baz">bar ...

Creating an engaging user experience with a Django form

Creating a dynamic calculator <div id="calculator"> <h2>Calculate the price of sawing materials</h2> <form method="post" action="{% url 'products' %}"> {% csrf_token %} & ...

Redux state not reflecting changes until second click

My redux store has a simple boolean setup to track whether a sidebar is expanded or not. However, I'm encountering an issue where, even though the default value is false, clicking the toggle button outputs false first. Ideally, if it's initially ...

Is it possible to incorporate an editable text feature within react-moveable? (Allowing for both dragging and editing capabilities)

In React Movable box, the text can be dragged with a left click and edited with a right click using the "contentEditable" attribute. However, on smartphones, editing seems to be disabled and only dragging is possible. <div className="move ...

The jQuery Code in My Updated HTML Is Not Running Properly

Currently, I am working on a dynamic insert form for my website. In order to achieve this, I am creating a button to append a new textbox that is supposed to be using the Select2 plugin. However, when I use the jQuery append() function, the appended code d ...

Checkbox switching in an AngularJS Bootstrap table

Our development team is currently working on a table widget within ServiceNow and we are aiming to include the functionality to select or de-select all rows using a checkbox. Here is a glimpse of our current HTML structure: <table class="table table-st ...

Can a single camera be utilized for capturing two different scenes?

Hey there! I'm currently working on rendering two different scenes with a camera that moves in sync between the two. Here's what I'm trying to accomplish: I need to display two separate point clouds in two distinct scenes, but I want the ca ...

What is the best way to verify if a value matches the container ID in Vue?

I am trying to create a condition where a property is checked against the ID of a div container. If they match, I want to display the container. For example, in the code snippet below, I need to compare the activeWindow property with the div id. If they a ...

In Ruby on Rails, ensure to trigger the ajax:beforeSend and ajax:complete events when using the link_to method with the remote

I'm currently developing a web app using Ruby on Rails as the framework. We have been utilizing the link_to method with remote true for all partial renders, following instructions provided in this helpful resource. However, I am looking to associate t ...

Select the radio button upon input alteration

Sign in image How can I automatically select the 'Yes' option button in the controller when a user starts typing in the password field? <!-- views/index.html --> <label for="optionsRadios1"> <input type="radio" name="optionsRa ...

Tips on choosing a dropdown option from an AngularJS application with Selenium in Java by utilizing text

Check out the HTML source for the dropdown menu Here is my custom function for selecting a value from a dropdown in an AngularJS application public String selectDropdownValue(String locatorName1, String locatorName2, String strtext) { try ...

Tips on ensuring Angular calls you back once the view is ready

My issue arises when I update a dropdown list on one of my pages and need to trigger a refresh method on this dropdown upon updating the items. Unfortunately, I am unsure how to capture an event for this specific scenario. It seems like enlisting Angular ...

Transmit collection of information to mqtt using Node.js

I'm facing an issue with sending an array of data from my node to the MQTT server. Although I have a receive function that is working fine, I'm unable to get it working in the opposite direction. var message = new Array(); message[0] = 108 ...

Sharing server object in expressJS with another file through module.exports

As I work on my expressJS app, I encountered a situation where I needed to share the server object with another file. To achieve this, I decided to create the server in my app.js file and then expose it to one of my routes. var server = http.createServer( ...

Create a duplicate of a React component that utilizes the forwardRef method

Imagine you have a foundational component that utilizes forwardRef in this manner: const BaseMessage = React.forwardRef((props, ref) => ( <div ref={ref}> {props.icon} <h2>{props.title}</h2> <p>{props.message ...

By setting `queue: false` when calling jQuery's `show()` method, you can

When looking at the code below, it is clear that even though showLoader is the first call, the loader does not appear immediately. This delay is due to the fact that heavyLifting function is blocking the UI thread. function onClick() { showLoader(); ...

Error message: "Window is not defined in Next.js"

Can anyone help me with this issue I'm experiencing: 'window is not defined' error? useEffect(() => { const handleScroll = () => { if(typeof window !== 'undefined') { // scrolling dete ...

Encountering a problem with $state.go in conjunction with ui-router: the URL successfully transitions to the new state, but the HTML content for the new view fails to

I'm facing a situation where I have an index.html page with two views: View1.html on the left and view2.html on the right. However, when a record is selected in the left view, I want to switch the right view from view2.html to view3.html. Currently, ...

How to resolve undefined Axios Authorization headers in Vue.JS and Node.JS interactions?

Encountering an issue while trying to set authorization headers for my axios instance. Here is the code snippet from my Vue.JS application running on http://localhost:8080 : axios.defaults.headers.common['Authorization'] = 'Bearer ' ...