How to Dynamically Set AngularJS Filter (like date or currency) Using Variables

When working with Angular, it's possible to easily apply filters to format variables, like so:

{{ myDate | date }}
{{ myMoney | currency }}

But, is there a way to dynamically set the filter type in a more flexible manner as shown below?

// controller 
$scope.myFilter = 'date';

// view
{{ myVar | myFilter }}

Situation: I am retrieving tabular data from my server along with metadata. I aim to display information such as dates, money, or numbers without manually specifying the columns.

For a simple illustration of this issue, check out this non-functional Plunker demo: http://plnkr.co/edit/SjYLKKUZcTjzRFhbsjK0

Answer №1

An alternative approach would be to consolidate your filters within a 'table cell filter' or a similar structure, where you can toggle different filters based on a designated parameter that can be controlled programmatically.

Here is an example for reference:

http://plnkr.co/edit/1DGOC1gFZiFyGAQRCIhk?p=preview

Incorporating this into your template:

  <ul>
    <li ng-repeat="value in values">{{value | myfilter:myFilterType }}</li>
  </ul>

The custom filter function:

app.filter('myfilter', function() {
    return function(input, type) {
    switch(type) {
        case 'uppercase':
          return input.toUpperCase();
        case 'lowercase':
          return input.toLowerCase();
        case 'date':
          return input.toString('dddd, MMMM ,yyyy');
        }  
    };
});

If necessary, additional filters can be loaded and implemented within this main filter function to maintain code cleanliness and avoid repetition.

Answer №2

One can implement filters programmatically, although achieving it that way may not be feasible. If you are comfortable with specifying filtered values within the controller, you could approach it similar to this:

JavaScript:

var app = angular.module('angularjs-starter', []);

app.controller('MainCtrl', function($scope, $filter) {

  $scope.values = [new Date(-1), new Date()];

  $scope.myFilter = 'date';

  $scope.$watch('values', function(values){
    $scope.filteredValues = [];
    if(!angular.isArray(values)){
      return;
    }
    angular.forEach(values, function(value){
      $scope.filteredValues.push($filter($scope.myFilter)(value));
    });
  });

});

HTML:

<div ng-controller="MainCtrl">
  <ul>
    <li ng-repeat="value in filteredValues">{{value}}</li>
  </ul>
</div>

Plunker.

Answer №3

If you're looking for a more straightforward approach, consider invoking a function when displaying the value. This way, you have the flexibility to leverage the $filter service and incorporate your own custom logic as needed. Take a look at this example on Plunker.

app.controller('MainCtrl', function($scope, $filter) {
  $scope.values = ['Test #1', 'Test #2'];

  $scope.myFilter = 'uppercase';
  $scope.myFilterFn = function(value) {
    console.log(value);
    var filter = $filter($scope.myFilter);
    console.log(filter);
    return filter(value);
  };
});

Template:

<body ng-controller="MainCtrl">
  <p>{{myFilter}}</p>
  <button ng-click="myFilter = 'uppercase';">Uppercase</button>
  <button ng-click="myFilter = 'lowercase';">Lowercase</button>
  <p>
    <ul>
      <li ng-repeat="value in values">{{myFilterFn(value)}}</li>
    </ul>
  </p>
</body>

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

The utilization of Django's template tags in conjunction with AngularJS

I'm facing a small puzzle - within Django's template, I have the following line of code: {% if x == y %} sth {% endif %} The "x" variable belongs to Django, while "y" is an angularjs variable. I know that one can modify the $interpolateProvider ...

The number of child notes can vary depending on the browser being used

Having an issue with a JavaScript function that is supposed to read an XML file. function readXML() { alert("readXML"); if(xmlDoc.readyState == 4 || xmlDoc.readyState == 'complete') { for(var i=0; i < xmlDoc.getElementsByT ...

Can you please guide me on retrieving information from an API using HTML, CSS, and JavaScript?

My task is to develop a web application using HTML, CSS, and JS with the following functionality: Retrieve a list of users from this API: https://jsonplaceholder.typicode.com/users. Upon clicking on a user, show a list of albums associated with that user ...

Is there a way to showcase the legend in a pie chart with two columns?

Is there a way to show the legend in two columns within the pie chart? Here is my JSfiddle link for reference: http://jsfiddle.net/Cp73s/2185/ itemStyle: { width:200, font: 'Helvetica Neue' ...

The File is not being successfully sent to the controller in MVC due to AJAX returning an undefined value

I recently created an AJAXUpload method within a cshtml file in my C# MVC project: function AjaxUpload(url, method, data, successFunction, errorFunction, skipErrorDlg) { $.ajax({ contentType: false, processData: false, url: url ...

Bar graph constructed using a pair of div elements

I extracted two values from an array: $target = $data->data[2][32][3]; For this particular example, $target = 9.83%. $clicks = $data->data[1][32][3]; And in this case, $clicks = 7.15%. I have created a bar-like chart using three main div elements ...

Executing an xajax/ javascript function simultaneously

Is there a way to simultaneously execute the same function? Here is an example: function convert_points() { show_loading(); xajax_ConvertPoints(); xajax_GetRegularGamingCards(); } When xajax_ConvertPoints is called, there seems to be a mill ...

The update function in model.findByIdAndUpdate() is failing to make changes

I am struggling to update a user model with new data using findByIdAndUpdate(). Despite my efforts, the model does not reflect the changes made. Below is the code snippet where I am attempting to use findByIdAndUpdate() to add an object: const User = ...

Ensuring JS consistently monitors changes in value

Is there an equivalent of (void update) in Unity that is called every frame in Web Development (using JavaScript)? "I want it to continuously check if certain values have changed and then update them accordingly." let governmentprice = parseFloat(select ...

What is the best way to retrieve a value from a function that contains multiple nested functions in Javascript?

The issue at hand is my struggle to extract a value from a nested method and utilize it outside of its parent method. I am aiming for the output of "console.log(someObjects[i].valueChecker);" to display either "true" or "false," but instead, it simply retu ...

What is the best way to position the list element to align with the top of a div container?

To see a live example, visit this link. My goal is to create a line that separates two li elements within a nested ul. However, the line ends up taking the width of the container ul instead of the div containing the entire structure. In the provided examp ...

Exploring the Power of Modules in NestJS

Having trouble with this error - anyone know why? [Nest] 556 - 2020-06-10 18:52:55 [ExceptionHandler] Nest can't resolve dependencies of the JwtService (?). Check that JWT_MODULE_OPTIONS at index [0] is available in the JwtModule context. Possib ...

Implementing a persistent header on a WordPress site with Beaver Builder

My website URL is: . I have chosen to use beaver builder for building and designing my website. I am in need of a fixed header that can display over the top of the header image. Here is the code snippet that I currently have: <div id="header">html ...

What is the best way to assign an object variable within an array state?

My current state looks like this: const [tags, setTags] = useState([{id: 1, label: "random"}, {id: 2, label: "important"}]) const [input, setInput] = useState("") const [selectedTag, setSelectedTag] = useState([]) In addition ...

Tips for identifying tablet devices using the deviceDetector module in AngularJS

Having an issue with a Samsung Tablet. I need to display certain content for mobile devices, but not tablets. Device detection results: - isMobile(): true - isTablet(): false Here is the detailed data from the module: {"raw":{"userAgent":"Mo ...

Achieving two-way data binding in a directive without using an isolated scope

Implementing scope: { ... } in a directive creates an isolated scope that doesn't inherit from its parent. However, my usual practice has been to utilize this for easily declaring HTML attributes with bi-directional data binding: scope: { attr1: ...

Utilize Protractor to extract the text within a specified span element

Is it possible to check if the text of the span within the button is "Vigente" using expect and Jasmine? If so, how can I achieve this? <button _ngcontent-hke-28="" class="btn btn-success disabled" tabindex="-1"> <span _ngcontent-hke-28="" class= ...

"Exploring the method of aggregating markers into a single point when zoomed out using Google Maps API

My web app features a Google Maps view. I have designed custom markers with unique info views for each one. As users zoom out, I want to avoid cluttering the map with numerous individual markers. Instead, I would like to group them together with a number ...

Tips for uploading information and posting it on a different page with mongoDB and Node.js

I am looking to implement a feature on a website where data is submitted to MongoDB from one page, and then retrieved and displayed on another page. The technologies I am working with include node.js, express, Mongoose, and MongoDB. Currently, the data is ...

Utilizing the @Component decorator in AngularJS version 1.5.5

Struggling to locate a quality code example of a component utilizing AngularJS 1.5.5 (NOT Angular 2.0). Can anyone confirm if Angular 1.5.5 supports decorators such as @Component or @Injectable, and if so, could you provide a helpful code snippet? I' ...