Tips on dividing the information in AngularJS

Sample JS code:

$scope.data={"0.19", "C:0.13", "C:0.196|D:0.23"} 
    .filter('formatData', function () {
        return function (input) {
            if (input.indexOf(":") != -1) {
                var output = input
                    .split('|')
                    .map(function (value) {
                        var splitValues = value.split(':')
                        return splitValues[0] + ':' + (Number(splitValues[1]) * 100) + "%"
                    })
                    .join()
                return output;
            } else {
                return input * 100 + "%";
            }
        }
    })

Example HTML code:

<h1 ng-repeat="item in data|formatData">{{item}}</h1>

Desired output:

"19%""C:13%""C:19.6%|D:23%"

Error encountered when running the code:

TypeError: input.indexOf is not a function

Looking for solutions to properly handle the data separation within AngularJS.

Answer №1

After making some adjustments to your code, I was able to achieve the desired result.

Below is the revised HTML code:

<h1 ng-repeat="x in items track by $index">{{x|customFilter}}</h1>

The values of the variables are as follows:

$scope.items=["0.19","A:0.13","B:0.196|C:0.23"];

Here is the custom AngularJS filter that I implemented:

.filter('customFilter', function () {
    return function (input) {
        if (input.indexOf(":") != -1) {
            var output = input
                .split('|')
                .map(function (val) {
                    var splitVal = val.split(':')
                    return splitVal[0] + ':' + (Number(splitVal[1]) * 100) + "%"
                })
                .join('|')
            return output;
        } else {
            return input * 100 + "%";
        }
    }
})

Answer №2

I have made some adjustments to your code in order to achieve the desired outcome as indicated. Please review the updated code provided below. For a clearer understanding, I have also prepared a fiddle which can be accessed here

Controller:

.controller('FilterController', function ($scope) {
  $scope.records = ["0.19","C:0.13","C:0.196|D:0.23"];
});

Filter :

.filter('filterOutput', function () {
        return function (inputArray) {
         return inputArray.map(function (input){
                 if (input.indexOf(":") != -1) {
                var out = input
                    .split('|')
                    .map(function (v) {
                        var s = v.split(':')
                        return s[0] + ':' + (Number(s[1]) * 100) + "%"
                    })
                    .join('|')
                return out;
            } else {
                return input * 100 + "%";
            }
         });
        }
    });

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

Guide on organizing users into groups and filtering them using Firestore's reference field type

I currently manage a small group of employees with plans to expand in the future. To streamline operations, I am looking to implement a grouping feature that allows users to sort employees based on their assigned groups. Although I thought about using the ...

Creating elegant Select Dropdown Box in AngularJS without relying on images

I am currently working on an angular page and have implemented a dropdown with ng-Options to fetch and set values successfully. However, I am now looking to enhance the appearance of this dropdown. After exploring options like ui-select, I realized that be ...

Child component in Angular2 makes an observer call to its parent object

Let me try to explain this in the best way possible. I have a service that includes an observable class responsible for updating itself. This observable class needs to be pushed out to the app using the observer within the service. How can I trigger that ...

How can you determine the number of elements that match in two arrays?

As a coding newbie, I'm looking to create a JavaScript function that compares two arrays and assigns a score based on the number of matching elements. However, when I attempt to run it in Chrome's console, I receive an error message stating that ...

Implementing a permanent class following an incident

Is it possible to dynamically add a class to an element when an event occurs rather than based on a condition? For example, I have a td that displays a variable. <td>{{myVar}}</td>//myVar=10 When the variable changes to myVar=15, I want to ad ...

Express.js does not recognize the req.query value

Incorporating Stripe Checkout functionality into a MERN application has been the focus of my recent project. Upon successful payment by a customer, they are directed to a checkout success URL where the CheckoutSuccess page is displayed. Additionally, Stri ...

Sending information to varying view/module - AngularJS

I am relatively new to AngularJS, so my question may seem quite basic. In one of my views, I have a link that, when clicked, calls a service to retrieve data. In the controller, I am using $location to change the view and update it with the data fetched f ...

The image is not appearing in my small AngularJS application

I have developed a small application that converts Fahrenheit to Celsius and I am trying to display a relevant image based on the Fahrenheit temperature input. However, I am facing difficulties in getting the image to display correctly. Can someone please ...

Laravel validation successfully validates Vanilla AJAX request, but the controller does not receive the values

Currently, I am utilizing AJAX (vanilla JS) to send a form to a Laravel 5.5 controller for searching the Amazon products API. The AJAX is sending the correct keywords and category inputs, but the controller is not receiving them. Even though the request p ...

Is there a problem with textbox support for multi-line strings?

I'm having trouble getting a textbox to display multiple lines of text. For instance, when I copy three lines of text from Microsoft Word and paste it into the textbox, only the first line appears. The other two lines are not showing up, and I'm ...

Error message: "Ajax script is failing to run"

Currently I am delving into the world of Ajax and have encountered a minor issue. I've been attempting to make a POST request to a Django backend using ajax, but strangely enough, the alert isn't showing up on screen. Furthermore, upon inspectio ...

Discover the magic of Bootstrap 3.0 Popovers and Tooltips

I'm struggling with implementing the popover and tooltip features in Bootstrap. While I have successfully implemented drop downs and modals, the tooltips are not styled or positioned correctly as shown in the Bootstrap examples, and the popover featur ...

The art of effectively conveying arguments to the callback function

Here's a react App component that takes in a settingsobj object along with a callback function: export const settingsObj = { handlers: { onClick: (e, dispatch) => { console.log('Click event triggered from settingsObj', e); dispat ...

Issue encountered: Object is not functioning properly with Node.js AuthenticationExplanation: A TypeError occurred

As a newcomer to Stack Overflow, I am doing my best to ask this question clearly. I am currently following a tutorial step by step ( http://scotch.io/tutorials/javascript/easy-node-authentication-setup-and-local ) but I encountered an issue after the thir ...

Display the data returned from a computed property PromiseResult using VueJS

After calculating the property shown below, it will output res, which is a Promise object. The reason I cannot place this script inside the created() or mounted() hook is due to the fact that this.selectedObject is null at that time. I am satisfied with t ...

I am experiencing some issues with my AngularJS JavaScript code. The root scope is updating correctly, but the other two scopes are not working as expected. Can

My attempt at writing AngularJS JavaScript code seems to be malfunctioning. While the root scope updates properly, the other two scopes FirstCtrl and SecondCtrl do not update as expected when the root scope is updated. I would like all three scopes to upd ...

What methods can be used to disable the back button functionality within an iframe?

I am facing an issue with embedding YouTube links on my webpage using iframes. When a user clicks on the link, it plays the video in the iframe. Below is the HTML and jQuery code I am using: HTML: <a href="http://www.youtube.com/embed/Q5im0Ssyyus"> ...

Sending JSON data from AngularJS to Laravel Controller through POST request

I have encountered an issue while using AngularJS to send POST data to a Laravel controller for saving into a database. The problem lies in the incorrect parsing of data from AngularJS to Laravel. The data being passed looks like this: $scope.invoice_ite ...

Providing an Angular Application using NginX

My Angular application has a specific structure that I usually deploy using an Express server. However, this time I need to deploy it with Nginx on a DigitalOcean instance. As someone new to Nginx, I'm unsure about how to set this up. Here is the init ...

Struggling to make the grunt.js task for postcss with autoprefixer function properly

I am currently facing issues with using postcss in conjunction with autoprefixer-core. Even though the css is being generated correctly, autoprefixer doesn't seem to be applying any prefixes. I have already installed postcss and autoprefixer via NPM ...