Preparing the data before displaying it

I have a data display in the view that needs to be formatted first. Previously, I used val.toFixed(2) which worked fine for numbers, but when letters were included with the numbers, the formatting didn't account for them and only displayed the numbers.

Therefore, I need a solution that can handle both letters and numbers, where only the numbers require formatting like this: 234235.34.

Below is some of the code snippet I am currently using:

<table>
    <tr>
        <th ng-repeat='header in headers'>{{header.th}}</th>
    </tr>
    <tr>
        <td ng-repeat='data in headers'>
          <div ng-repeat='inner in data.td'>
            <span ng-repeat='(prop, val) in inner'>{{val.toFixed(2)}}</span>
          </div>
        </td>
    </tr>
</table>

This functionality is controlled by the following controller:

$scope.LoadMyJson = function() {
      // Code logic here
};

You can find a working example on this Fiddle.

Currently, the table is displaying correctly but missing the name column due to the use of the toFixed method.

If you have any ideas or suggestions on how to approach this issue, please let me know. Thank you!

Answer №1

Add a personalized filter to implement in your template.

<table>
    <tr>
        <th ng-repeat='header in headers'>{{header.th}}</th>
    </tr>
    <tr>
        <td ng-repeat='data in headers'>
          <div ng-repeat='inner in data.td'>
            <span ng-repeat='(prop, val) in inner'>{{val|formatValue}}</span>
          </div>
        </td>
    </tr>
</table>


angular.module('whatever').filter('formatValue', function () {
  return function (value) {
    if (isNaN(parseFloat(value))) {
      return value;
    }

    return parseFloat(value).toFixed(2);
  } 
});

Answer №2

If you want to display formatted data in your view using AngularJS as your MVC frontend framework, try this method:

  • First, create a filter within your Angular application.
  • Next, include the filter in your index.html file.
  • Finally, use the filter in your code like this: {{somedata | filterName}}

This simple Angular filter can help solve your problem:

angular.module('app')
.filter('formatHeader', function() {
    return function(data) {

        if(angular.isNumber(data)) {
            return data.toFixed(2);
        }

        return data;
    }
});

To implement this filter, use it in your code like this:

<table>
<tr>
    <th ng-repeat='header in headers'>{{header.th}}</th>
</tr>
<tr>
    <td ng-repeat='data in headers'>
      <div ng-repeat='inner in data.td'>
        <span ng-repeat='(prop, val) in inner'>{{val | formatHeader}}</span>
      </div>
    </td>
</tr>

For further reading, check out these references:

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

How can I load a .json file into JavaScript without inserting it directly into the code?

Currently, I am dealing with a lengthy JSON snippet that resembles the following: { "section: [ [stuff] ] } To incorporate this into my JavaScript code, I currently use the following approach: var obj = { // {All the stuff from above} } My ...

In order to ensure functionality on Firefox 3 and Opera, it is essential to include multiple <script> tags and the <!-- //required for FF3 and

I have utilized Spring Roo to create a basic web project. The user interface is JSP-based with a Tiles layout. Upon examining the default layout code, I noticed that the script tags were defined as: <script src="${dojo_url}" type="text/javascript" > ...

I'm experiencing a challenge with Next.js where I am unable to use return within

My code was functioning properly with if-else statements in run dev, but encountered issues when running build. The if-else statements stopped working, prompting me to explore alternative ways of conditionally rendering a page. A new approach seemed promis ...

Using React Native to implement Firebase onSnapshot with FlatList pagination

INTRODUCTION I have a collection of items stored in FireStore with the "date" property. On the client side, I'm using a FlatList to display these items ordered by date, starting with the most recent item at the top. The challenge I'm facing is ...

What is the best way to establish my permit requirements on a monthly basis?

An employee is only allowed to request up to 3 permits per month. If they need a fourth permit, they will have to wait until the following month. Here is my table structure for permissions: Permissions id (integer), format (text), date_r ...

Ionic Vue Modal displays duplicated content

Trying to implement a modal in an Ionic Vue app, I encountered a strange issue where the content is being displayed twice. This problem persists even when using the example code provided on the Ionic website: The modal content component looks like this: & ...

Potential dangers involved in sending HTML content through an AJAX request over a secure HTTPS connection

I am exploring the idea of dynamically loading HTML content, such as updating a Bootstrap modal dialog's contents using AJAX calls instead of refreshing the entire page. However, before I proceed, I want to understand the potential risks involved and ...

Struggling with the integration of a custom login feature using next-auth, leading to being constantly redirected to api/auth/error

Currently, I am facing a challenge while working on my Next.js application. The issue lies with the authentication process which is managed by a separate Node.js API deployed on Heroku. My objective is to utilize NextAuth.js for user session management in ...

Is there a way to showcase a PHP code snippet within JavaScript?

This piece of code contains a script that creates a new div element with a class, adds content to it using PHP shortcode, and appends it to an Instagram section. Check out the image here <script> let myDiv = document.createElement("div"); ...

Having trouble accessing a website that is embedded within an iframe, and experiencing issues with several ajax post requests not functioning properly within the iframe specifically on Chrome

I am currently dealing with a situation where I have two distinct websites, (constructed with PHP) and (also a PHP site). To integrate them, I have embedded site1 inside site2 using an iframe. <iframe src="https://site1.com" seamless width= ...

What is the best way to transfer information from an old JSON file to a new JSON file using JavaScript

I have a JSON file and I need to extract the content of "data" where the provider is "AXIS DATA" into a new JSON file. How can this be achieved? Here's what I've attempted: First, I convert it using JSON.parse and then search for the desired da ...

Ways to transfer ID to a different HTML page

I have some Javascript code in a file named nextPage.js. When this code is executed by clicking on something, it should transfer the value of category_id to another page called reportlist.html. Can you please provide assistance with this? var base_url = " ...

What is the best way to ensure that custom JavaScript and CSS files in Sphinx are always loaded with the most recent changes

Within the configuration file conf.py for Sphinx, I have specified the following: html_css_files = ['css/custom.css'] html_js_files = ['js/custom.js'] However, any alterations made to custom.js or custom.css do not immediately appear i ...

"Encountering a delay in the passport authentication callback process

After multiple attempts to solve this issue independently, I have turned to the Stack Overflow community in search of guidance. I am implementing user authentication using passport. It has already been initialized in my main express.js file following the ...

Refresh the dropdown menu selection to the default option

My HTML dropdown menu includes a default option along with dynamically generated options using ng-options. The variable dropdown is bound to the dynamic options, not the default one. <td> <select ng-model="dropdown" ng-options="item as item.n ...

The error "TypeError: ollama.chat is not a function" has occurred when trying to use the ollama module in

Currently, I am grappling with a Node.js project that requires me to utilize the ollama module (ollama-js). The problem arises when I invoke the async function chatWithLlama() which contains ollama.chat(), resulting in the following error being thrown: Ty ...

How to harness the power of loops in JavaScript

Having trouble getting this code to repeat a CSS transition properly. for (var i=0 ; i<4 ; i++){ setTimeout(function() { $('#top-left').css('margin', '45px 0 0 45px'); $('#top-mid' ...

Versatile dataTable designed to seamlessly integrate with various data structures

My task is to develop an ajax dataTable that can handle a variety of data sources with different column names and data types. The challenge lies in the fact that I cannot predefine the column names or data types when coding the dataTable, as each data sour ...

Why isn't the mounted() lifecycle hook being triggered in my Vue 3 component?

I am struggling with a simple Vue 3 component that closely resembles some examples in the documentation. Here is the code: // Typewriter.vue <template> <div id="wrapper"> <p>{{ text }}</p> </div> </templa ...

Generating an array in Javascript using JSON

I've been doing a lot of research, but I can't seem to find a solution that works for me. My goal is to retrieve the next four bus arrival times for a specific bus stop using an application that reaches out to an API returning JSON data. The issu ...