Is it possible to retrieve the user's input value within a custom filter? I am attempting to access the user's input number either from the controller or

I am a beginner in AngularJS and I am attempting to filter data based on temperature by subtracting the user input (x) from the currentTemp variable. However, I am unsure how to access the user input value in a custom filter. This approach may work for now, but I am also considering implementing a similar logic for dates in the future. Feedback on the feasibility of achieving this using a custom filter is appreciated, as well as any alternative logic suggestions.

http://plnkr.co/edit/Qzne7wfnSa2keRcvbUUV?p=preview

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

app.controller('MainCtrl', function($scope) {
  
  $scope.sensordata = [{name:'Rob',"Date": "2014-02-16T00:00:00.000Z","Temp":42},
  {name:'Bob',"Date": "2012-02-16T20:27:11.507Z","Temp":50},
  {name:'Tom',
  "Date": "2012-02-16T20:27:11.507Z","Temp":60},
  {name:'Sinclair',"Date": "2012-02-16T20:27:11.507Z","Temp":65}];
  $scope.condEqual=function(){
  
  var x = document.getElementById("myNumber").value;
  document.getElementById("demo").innerHTML = x;
  }
  
});

app.filter('tempo', function() {
    return function( items, field ) {


      var filtered = [];
  var x=2;
     var currentTemp=62;
       
      angular.forEach(items, function(item) {
        if (item[field]<= currentTemp){
          filtered.push(item);
        }
      });
      return filtered;
    };
});
<!DOCTYPE html>
<html ng-app="tempfilter">
  
  <head lang="en">
    <meta charset="utf-8">
    <title>DateFilter</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
    <script>
      document.write('<base href="' + document.location + '" />');
    </script>
    <script src="script.js"></script>

</head>
  
  <body ng-controller="MainCtrl">
  <input type="number" id="myNumber" value="2">
<button ng-click="condEqual()">Enter</button> </br>
<p id="demo"></p>
   Filtered list:
<ul>
      <li ng-repeat="s in sensordata | tempo:'Temp'">{{s.Date|date:'MM/dd/yyyy'}}
      {{s.name}}
  {{s.Temp}}

    </li>
    </ul>

Full List:
<ul>
      <li ng-repeat="s in sensordata ">{{s.Date|date:'MM/dd/yyyy'}}
      {{s.name}}
  {{s.Temp}}

    </li>
    </ul>
  </body>

</html>

(The main objective here is to filter data based on date, where the user can input a value (e.g., 3) and have all data displayed from three days ahead of the current date. For example, if today's date is 2/19/2015 and the user inputs 3, the filter should show data from the last three days. Currently experimenting with temperature filtering, but plan to apply the same logic for dates in the future).

Answer №1

Instead of:

Grab the value with this line of code:
var x = document.getElementById("myNumber").value;

Consider using this instead:

Set the value directly in your Angular controller:
$scope.filter = { value: 2 };

And rather than:

Update the HTML element like so:
document.getElementById("demo").innerHTML = x;

Do this in your HTML markup:

<input type="number" id="myNumber" ng-model="filter.value">

<p id="demo">{{ filter.value }}</p>

No need for a button or extra function, Angular's two-way data binding handles updates automatically.

Finally, pass filter.value as a parameter to your custom filter.

Create a custom filter in your app module:
app.filter('tempo', function() {
    return function(items, field, value) {
        var filtered = [];
        angular.forEach(items, function(item) {
            if (item[field] <= value){
                filtered.push(item);
            }
        });
        return filtered;
    };
});

Apply the filter in your template:

<li ng-repeat="s in sensordata | tempo:'Temp':filter.value">

Answer №2

Connect your input to a model and then directly utilize that model in your personalized filter as shown below

<ul>
   <li ng-repeat="s in sensordata | tempo:'Temp':myNumber">{{s.Date|date:'MM/dd/yyyy'}}
      {{s.name}}
      {{s.Temp}}
   </li>
</ul>

If you wish to assign a default value to your input, initialize your model within the controller like this: $scope.myNumber=62

OR

Create a function in your controller and use it as a filter like so:

<ul>
      <li ng-repeat="s in sensordata | filter:filterByTempo('Temp',myNumber)">{{s.Date|date:'MM/dd/yyyy'}}
      {{s.name}}
      {{s.Temp}}

    </li>
    </ul>

Filter Function

$scope.filterByTempo = function(field,tempo) {
    return function(item) {
      if (item[field]<= tempo){
        return true;
      }
      return false;
    }
  }

View the updated Plunker (Using Angular Custom Filter)

Check out the revised Plunker (Using Filter Function)

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

Having trouble deploying my VueJS application on Heroku. Encountering the error message "npm ERR! missing script: start" in the Heroku logs and seeing "Application error" on my webpage

I recently deployed my VueJS app, "Twitter Clone," on Heroku with the expectation of having a live version available. The data was successfully synced from my GitHub repository to Heroku. However, I encountered an issue. Visiting shows an error message ...

Is the HTTP request from the browser being recorded?

When sending an HTTP request using fetch to website A from the Chrome console on website B, is it possible for website B to track any information about that request, or is it strictly client-side? In other words, can website B detect this action? Thank yo ...

Can the rxjs take operator be utilized to restrict the number of observables yielded by a service?

As someone who is just starting to learn Angular, I am working on a website that needs to display a limited list of 4 cars on the homepage. To achieve this, I have created a service that fetches all the cars from the server. import { Response } from &apos ...

Is there a way to obtain the tasklist result of exec() from child_process and convert it to JSON format?

When I use the tasklist command with child_process, the stdout returns processes in Unicode string format that is not easily queryable. Here is the code snippet: var exec = require('child_process').exec; ... exec('tasklist', function( ...

I am currently working on determining whether a given string is a palindrome or not

I'm currently working on a function that checks whether a given string is a palindrome. So far, my tests are passing except for the following cases: (_eye, almostomla, My age is 0, 0 si ega ym.) This is the function I've implemented: function pa ...

Is there a way to create a popover menu in VueJS without using JQuery

I found exactly what I need in this helpful answer. It demonstrates a menu appearing when clicking on a table row. The dilemma is that it relies on JQuery... Therefore, I am curious if achieving the same functionality without JQuery is possible. Maybe thr ...

Switch up the link color when it pops up

Is there a method to change the link color to gray without encountering glitches like on my site, where it mistakenly shows "Quick Nav."? Click here to view the page with the glitch I only want this particular link to be bold and not any other links. He ...

Constantly loading image with Meteor HTTP request

Within my Meteor application, I am attempting to dynamically load a random image from an API which returns JSON data structured like this: { "id":2026 "url": "https:// ... " , "large_url":null, "source_id":609, "copyright":"CC0", "site":"unsplash" } ...

What is the best method for creating an HTML table using a Javascript function in PHP?

When working with a PHP file to generate a table based on SQL query results, I encountered an issue where only one incorrect row is returned. If anyone has a basic idea of what might be happening, it would be greatly appreciated. This is my HTML Code: &l ...

retrieving information from a secondary window

Currently, I am working on a project and have come across an issue. Please take a look at the following code snippet: <iframe name="stus" id="stus" style="display:none;"></iframe> <form name="water" id="water" method="post" autocomplete="of ...

Exploring the mechanics of an Ajax call

Feeling a little lost in the call flow of Ajax - can anyone provide some guidance? This is my HTML: <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="myFunction()">Change Content</but ...

Is AjaxMin's EvalTreatment changing the game for JavaScript minification?

While minifying my project using the AjaxMin.dll with the default settings on every build/deployment, I ran into a problem. One of our third-party JavaScript files contains an eval statement that references variables or parameters which, when minified, cau ...

Are there any potential drawbacks to utilizing fabricated attributes in HTML tags?

Imagine I have this HTML tag <a href=""></a> and then I decide to create a custom attribute <a lol="haha" href=""></a> Why would I do this? Well, it's so I can easily utilize that custom attribut ...

What is the best way to preload images from an array within another array?

I am encountering an issue with preloading images. for(y=0;slide_image.lenght;y++){ for(x=0;slide_image[y].lenght;x++){ var preload_image=new Image(); preload_image.src=slide_image[y][x];} } When I use preload_image.src=slide_image[x] alon ...

Chakra UI: How come the tooltip is appearing in the top left corner of the screen instead of directly above the element?

CreatedByModal is a unique chakra modal that incorporates tooltips. However, I am facing an issue where the tooltip appears at the top of the screen instead of directly above the icon when hovering over the icons. You can see in the image provided that the ...

Emphasizes the P tag by incorporating forward and backward navigation options

My goal is to enable users to navigate up and down a list by pressing the up and down arrow keys. For example, if "roma" is currently highlighted, I want it to change to "milan" when the user presses the down arrow key. Here is the HTML code I am working w ...

Using curly braces in a fat arrow function can cause it to malfunction

Could someone provide insight into why this code snippet functions as intended: filteredArray = contacts.filter( (contact: Contact) => contact.name.toLowerCase().includes(term.toLowerCase()) ); while this variation does not: filteredArray = contact ...

Transforming this Rails form into an Ajax/JavaScript/jQuery format will eliminate the need for submission

I have developed a form in Rails that computes the Gross Profit Margin Percentage based on an input of Price. When a user selects the relevant product on the form and enters a price in the 'deal_price' field. A callback is triggered to retrieve ...

Having difficulty accessing $scope beyond the function

One of the functions in my code is called getMail() $scope.getMail=function(){ $http.get(APISource). success(function(data) { $scope.mail =data; }). error(function(data) { console.log("error"); console.log(data); }); } In the succe ...

Saving data to a database using jQuery Ajax when multiple checkboxes are checked

Looking for a solution to store checkbox values into a database using jQuery Ajax to PHP. https://i.sstatic.net/tdjm9.png To see a live demo, click here. The image above illustrates that upon checking certain checkboxes and clicking Update, the checkbox ...