AngularJS function for comparing operators

Just starting out with AngularJS and I've been given a small task to solve by my employer. Having some trouble with it, so hoping someone can lend a hand.

The task involves using comparison operators in ng-options along with a number field to filter results from a table of employees. For example, if the user selects 'greater than' in the ng-option and inputs '50' in the text field, the result should display employees whose age is greater than 50 from the data table. Any help would be greatly appreciated!

This is what I've attempted:

$scope.operators = [
            {
                field: "gt"
                title: ">"
                }
                , {
                field: "lt"
                title: "<"
                }
                , {
                field: "et"
                title: "="
                }
             ];
        $scope.selected = $scope.operators[0];
        app.filter('priceGreaterThan', function () {
            return function (input, price) {
                var output = [];
                if (isNaN(price)) {
                    output = input;
                }
                else {
                    angular.forEach(input, function (item) {
                        if (item.redemptions > price) {
                            output.push(item)
                        }
                    });
                }
                return output;
            }
        });

Answer №1

Hey there! Utilize the filter to perform all three operations effortlessly. Take a look at the code snippet below for reference.

Your filter is functioning well. I have enhanced it by adding an if else condition to execute different operations. Additionally, I have included a table to display the output. Instead of solely passing the price to the filter, I am now passing an object (

{price: price, operator: selected.field}
) which the filter uses to retrieve the price and operator. Kindly review my code and inform me if there are any concerns.

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

app.controller('MyController', function MyController($scope) {
  $scope.data = [{
    name: 1,
    redemptions: 100
  }, {
    name: 1,
    redemptions: 150
  }, {
    name: 1,
    redemptions: 200
  }, {
    name: 1,
    redemptions: 50
  }, {
    name: 1,
    redemptions: 1
  }, {
    name: 1,
    redemptions: 10
  }]
  $scope.operators = [{
    field: "gt",
    title: ">"
  }, {
    field: "lt",
    title: "<"
  }, {
    field: "et",
    title: "="
  }];
  $scope.selected = $scope.operators[0];
});

app.filter('priceGreaterThan', function() {
  return function(input, params) {
    var output = [];
    if (isNaN(params.price)) {
      output = input;
    } else {
      angular.forEach(input, function(item) {
        if (params.operator === "gt") {
          if (item.redemptions > params.price) {
            output.push(item);
          }
        } else if (params.operator === "lt") {
          if (item.redemptions < params.price) {
            output.push(item);
          }
        } else {
          if (item.redemptions == params.price) {
            output.push(item);
          }
        }
      });
    }
    return output;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller='MyController' ng-app="myApp">
  <input type="text" ng-model="price">
  <select name="operator" id="test" ng-model="selected" ng-options="x as x.title for x in operators"></select>
  <table border="1">
    <tr>
      <th>Name</th>
      <th>Redemptions</th>
    </tr>
    <tr ng-repeat="j in data | priceGreaterThan: {price: price, operator: selected.field}">
      <td>{{j.name}}</td>
      <td>{{j.redemptions}}</td>
    </tr>
  </table>
</div>

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

I am facing an issue where the code in the content script is not getting injected when the URL tab changes. Is there a way to resolve this problem?

Recently, I developed a chrome extension for a website that utilizes ajax calls for page navigation. This caused me to reload the page every time in order for the script to be injected. To circumvent this issue, I implemented the following approach: chrom ...

How to disable scrolling for React components with CSS styling

When incorporating a React component into my HTML, I follow this pattern: <html> <body> <div id=app>${appHtml}</div> <script src="/bundle.js"></script> </body> </html> Within my application, th ...

Determined margin value to replicate the maximum and minimum margin in CSS styling

When attempting to set the margin on an object to 20% with a maximum margin of 200px, I experimented with various methods: margin-left: calc(min(200px, 20%)); and max-margin-left: 200px However, neither property proved to be valid. Is there an alterna ...

Laravel is sending out the HTTP header text together with the payload response

My current setup involves using React and jQuery on the frontend like this: $.ajax({ url: ... method: 'POST', contentType: 'application/json', dataType: 'json', success: (response) => { ... }, error: (err) => ...

When typed into the search bar input box, text becomes reversed

I've encountered an issue where text entered into a text field appears in reverse order. For instance, when I type " Hi how are you ", it displays as " UYO REA OH HI ". How can this be resolved? I am using the silent WP theme and have tried inspecting ...

Publish a Reddit comment using programming code

I've been attempting to automate the process of posting a comment on Reddit using the Snoocore library. Below is the code I'm working with: function postComment() { var commentText = document.getElementById("response").value; ...

Creating a ToggleButton in C#Is a Togglebutton the

I am trying to create a togglebutton for a website with Microsoft Visual Studio and am not sure if this would be the correct code to apply. I am working in C#, so the button is going to be generated in C# (and a bit of jquery) code and eventually styled in ...

How to prevent Bootstrap Carousel from automatically sliding on mobile devices without using JavaScript

Is it feasible to halt the autoslide feature on mobile view through CSS? Perhaps using a media query for extra small (xs) screens and then adjusting a carousel element...? <div id="carousel" class="carousel slide" data-ride="carousel"> <!- ...

Restricting the movement of the mouse event

Is there a way to restrict the mousemove event to a specific area, such as a div located in the center of the page? Thank you in advance if (window.innerWidth > 765) if (matchMedia('(pointer:fine)').matches) $(document).ready(function() { $ ...

Reduce the width beyond the necessary limit

I'm struggling to adjust the width of an image to match it with the card size without stretching it or breaking the layout. Most solutions I've come across recommend using inline-block, but this doesn't work well for smaller images. It seems ...

The positioning of the jumbotron image is off-center

I'm facing an issue with the header code. The image is not centered properly when I switch between different sizes. Is there a way to ensure that the image is centered in all size views? <div class="jumbotron"> <img src="images/hea ...

Is it possible to rotate an image with a random angle when hovering in Angular?

I'm currently working on a photo gallery project and my goal is to have the images rotate when hovered over. However, I am experiencing difficulties in passing values from TypeScript into the CSS. HTML <div class="back"> <div cl ...

Enhance user experience with AngularJS Bootstrap autocomplete feature by automatically filling input box when hovering over dropdown options

I am currently implementing the AngularJs Bootstrap typeahead functionality. Typically, when we enter text that matches an option, the dropdown list appears. https://i.stack.imgur.com/395Ec.png What I aim for is to automatically fill the textbox with the ...

Responsive Image Resizing with Bootstrap for Smaller Screens

I'm struggling to resize a responsive image in Bootstrap using the carousel example on their official website. <div class="container"> <div class="other-div"> .... </div> <div id="carouselExampleCon ...

The web page's content remains hidden until it is scrolled into view, despite the fact that the page has finished loading

I'm a beginner with Angular and currently working on creating a website. On the following page , when viewed on mobile, I am experiencing an issue where the content doesn't load until it's brought into view by scrolling down the page. I am u ...

Is the Bootstrap navigation bar collapse button visible on larger screens?

How can I make my Bootstrap navbar collapse button work on big screens the same way it does on mobile devices? <nav class="navbar navbar-expand-md navbar-light bg-light"> <a class="navbar-brand" href="#">Default</a> <button ...

Problem with Bootstrap5 tooltips

Utilizing bootstrap 5 on my website, I encountered an issue with tooltips (taken from the official documentation website): https://getbootstrap.com/docs/5.1/components/tooltips/#examples Despite extensive searching on Google and Stackoverflow, none of the ...

What could be the reason my checkbox won't check using jQuery?

Currently, I am using kojs within my Magento 2 project. I have implemented a method that successfully shows and hides an input box based on user interaction. However, despite the function working as expected, the checkbox does not display its checkmark. D ...

The combination of jQuery and JavaScript targeting the element with the ID '#update1' is essential. Can someone please assist me with

comprehend my message <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css"> ...

Unable to utilize the rupee font within a select element on Chrome and IE8 browsers

Issues with displaying rupee font in select element on Chrome and IE8 I have implemented WebRupee for showing the Indian currency symbol. The font appears correctly when used within a <p> tag, but when placed inside a select option element, it only ...