Mastering the art of utilizing $filter alongside select in angular.js

Is there a way to switch between different filters based on the user's selected values? I have three filters ('largeNumber', 'Percentage', 'Bytes') and I want to toggle between these filters based on the selection made by the user. Currently, I am trying to implement the filter in my JavaScript code, but it is not functioning as expected. See the jsfiddle for reference.

Expected Output:

For example, if the user inputs 1200 and selects 'Large Numbers,' the expected output should be 1k.

View:

<div ng-controller="MyCtrl">
  <form role="form" class="form-inline">
  <div class="form-group">
    <input type="text" class="form-control" id="sample" ng-model="numberData" placeholder="Enter Number">
                 <select class="form-control inline" id="format" ng-model="numberType"
                  ng-options='type for type in selectType' ng-change="selected()">
                  <option style="display:none" value="" class='formOptions'>select a type</option>
                </select>
  </div>

</form>
 <h1> data here: {{numberData}}</h1>
</div>

JavaScript Code:

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

myApp.filter('largeNumber', function(){
    return function(number, decPlaces) {
    ...
    return number;
  }

  })
  
  function MyCtrl($scope, $filter) {
      $scope.selectType = ['Large Number', 'Percentage', 'Bytes']

    $scope.selected = function() {
    console.log($scope.numberType)
       return $scope.numberType

     };

    $scope.selectedType = $scope.selected()

    $scope.sendSelectedItem = function(){
       if($scope.selectedType == "Large Number"){
          return $filter('largeNumber')(0)
      }

    }
  }

Answer №1

Updates to be made in HTML:

<h1> Insert data here: {{formattedNumberData}} </h1>

Changes in Script: The following code is sufficient for the controller.

$scope.selectOption = ['Large Number', 'Percentage', 'Bytes'];

$scope.updateSelectedData = function() {
  if ($scope.dataType == "Large Number") {
    return $filter('largeNumber')($scope.rawData, 0);
  }
  // Add logic for other options or defaults here
}

$scope.updateDataDisplay = function() {
  $scope.formattedNumberData = $scope.updateSelectedData();
};

// Set the default type
$scope.dataType = "Large Number";

Issues in your code:

  1. The function $scope.updateSelectedData is defined but not called. It should be executed when an option is selected, applying the necessary filter and assigning the result to another scope variable.

  2. $scope.rawData is a raw value. Without applying a filter before assigning it to the h1 tag, it will simply display the input field's value.

Hope this clarifies things for you.

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

Validating a string using regular expressions in JavaScript

Input needed: A string that specifies the range of ZIP codes the user intends to use. Examples: If the user wants to use all zip codes from 1000 to 1200: They should enter 1000:1200 If they want to use only ZIP codes 1000 and 1200: They should enter ...

What is the reasoning behind defaultValue possessing the type of any in TextField Material UI?

According to the Material UI guidelines, the component TextField specifies that its defaultValue property accepts the type any. I decided to experiment with this a bit and found that in practice, defaultValue actually supports multiple types. You can see ...

Is it possible to deinitialize data tables (remove from memory)?

I'm currently utilizing data-tables (with jQuery) on my website. The particular data-table I have implemented seems to be consuming excessive memory in javascript, causing a slowdown in other functionalities. Is there a way for me to de-initialize th ...

The functionality of the ui sortable feature in Angular is not effective when used on a single-page website

My latest project involves using a single-page application. To connect the UI Angular library, I followed these steps: I started by adding the necessary scripts: <script src=.....jquery-1.9.1.js"></script> <script src=.....jquery-ui.js"> ...

I am struggling to add a list from these nested functions in Express, but for some reason, the items are not being properly

I am currently working with three nested functions and facing an issue where the last function is not returning the desired list of items. Interestingly, when I log the results of the last function within the loop, I can see the URLs that I need. However, ...

Tips for incorporating numerous visible arrows into your Three.js project by utilizing the THREE.ArrowHelper functionality

edited: specifying the use of ArrowHelper I am looking to create a multitude of arrows on a 2D plane to visually represent a vector field. Typically, there are around 20,000 vectors that need to be displayed. Although I am currently using THREE.ArrowHelp ...

Angular = encountering an incorrect array size limitation

I am encountering an issue with the function in my controller... $scope.pagerPages = function (n) { var i = Math.ceil(n); return new Array(i); } The n value is derived from an expression on the view and can sometimes be a fraction. This is why I ...

Ways to incorporate vector .svg images into a D3js tree diagram

var treeData = [ { "name": "Top Level", "parent": "null", "remark":"yes", "children": [ { "name": "Level 2: A", "parent": "Top Level", "remark":"yes", "children": [ { "name": "So ...

Utilize the push method to form a new array

var teamMembers = [ ['John D. Adams', '1959-1967', 'Ohio'], ['Dawson Mathis', '1971-1981', 'Georgia'], ]; To generate this dynamically, I am implementing the code below: var data = ne ...

Having trouble with routing in Angular

Attempting to create a REST API for the TodoApp built in Angular. I have successfully set routes for ADD, UPDATE, and GET ALL, but am encountering issues with the DELETE method. Here is my angular controller: angular.module('todoListApp') .contr ...

Assign a value using the select component from Material UI

I just finished creating a dropdown menu const [selectedValue, setSelectedValue] = useState(''); const handleSelectionChange = (e: any) => { //setSelectedValue(e) console.log('value', selectedValue) } .... <Fo ...

Issues detected between Angular and Express rendering operations

Having an issue with my angular code. It runs perfectly on its own, but when I try to access it on localhost with express, it only displays the HTML file. Here's my server code: var express = require('express'), app = express(); app ...

Learn how to efficiently execute a function multiple times using pure JavaScript

I am trying to create a tabbed content functionality with multiple elements. How can I utilize the same function for various elements declared in a variable? For example, I want to clone the parent div.tabs element with similar content but different ids an ...

Launching an embedded webpage in a separate tab within the main browser window

In my current setup, I have implemented an iframe within the main window. The iframe includes a form where users can input data and submit it. Currently, I achieve the submission with the following code: var openURL = '/results/finalpage'; windo ...

Creating a customized image modal in ReactJS that incorporates a dynamic slideshow feature using the

I am attempting to incorporate an image lightbox into my React application: https://www.w3schools.com/howto/howto_js_lightbox.asp Here is the link to the CodeSandbox where I have tried implementing it: https://codesandbox.io/s/reactjs-practice-vbxwt ...

Values in the list of onClick events are currently not defined

I'm having trouble importing a list component into my form and capturing the onClick event to submit the information. However, every time I click on the list, the data shows up as undefined. What could I be doing incorrectly? Here is the code for my ...

Managing a secure login page with Protractor

Our team is currently exploring how to implement AngularJs and Polymer components in a new web application. I am tasked with creating a UI automation suite for this project. After conducting extensive research, it seems that Protractor could be the right t ...

The functionality of anchor links created through ajax is not operating correctly

Issue: I am encountering a problem where I have a table filled via Ajax, containing local anchors. When an anchor is clicked, it should make a section visible and automatically scroll to it. This functionality works when manually filling the table, but not ...

Can one function be invoked from another function in Node.js?

As I delve into learning Node.js through the process of converting an existing Rails project, I find myself grappling with callbacks and the asynchronous nature of Node. It has been a challenging journey to wrap my head around these concepts. Initially, m ...

What methods do certain API services use to accept Authorization headers from any source?

Payment processing platforms like Stripe and Square provide the capability to include your API key in an Authorization header as a Bearer token. However, my understanding is that allowing credentials, such as the Authorization header, from all origins is ...