Removing and shattering data from a JSON file at a designated location in AngularJS

I have received json data that is structured like this (and unfortunately cannot be modified):

Desc: First data - Second data

My current method of displaying this data involves using the following code:

<div ng-repeat="b in a.Items">{{b.Desc}}</div>

However, I need to show 'Second data' below 'First data' without the hyphen separating them.

Currently, the display looks like this:

<div>First data - Second data</div>

But I require it to be displayed as:

<div><p>First data</p><p>Second data</p></div>

or

<div>First data<br/>Second data</div>

Is there an option or filter within angularjs that can help me achieve this formatting by breaking the string and removing the hyphen?

Answer №1

Utilize the $filter para separar o ângulo. É importante ter cuidado em casos onde a string não contém o caractere "-". Por isso, é recomendado o uso do $filter

var app = angular.module("App", []);
app.controller('AppController', function($scope) {
   $scope.a = {Items:["XX-BBB", "CCC-AAA", "-VVV", "FFF-"]};
}).filter('splitValue', function() {
    var indexAllItens = 0;
    return function(input, index) {
       console.log(input + ' ' + index)
        var data = input.split('-'), str = '';
        if(data.length >= index)
            str = data[index];
        return str;
    };
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App" ng-controller="AppController">
  <ul ng-repeat="b in a.Items">
     <li>{{b | splitValue:0}}</li> <li>{{b | splitValue:1}}</li>
  </ul>
</div>

Answer №2

To effectively tackle this issue, the recommended approach is to convert your data in the controller and then link the converted data to the scope.

However, if you're looking for a quick fix, you can try this:

<div><p>{{ b.Desc.split(' - ')[0] }}</p><p>{{ b.Desc.split(' - ')[1] }}</p></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

modify web API response type

I am currently developing a web API project and I need to customize the JSON type being returned. My aim is to return two arrays with a specific format as outlined below: Snippet from my controller public IHttpActionResult GetNOX(){ ------- ...

Transferring a Variable from Arduino to JavaScript

Is there a simple way to pass an Arduino variable as a JS variable? Let's say we have an integer Arduino variable called sensorData: int sensorData = analogRead(sensorPin); How can we transfer this value to a JavaScript variable? client.println(&quo ...

Can you provide steps on converting a Facebook response into a JSON formatted string?

I'm attempting to receive query responses from Facebook and match them to a user-defined class: Here is the class structure I have: class FBStory { @Field private String application_id; @Field private String applicati ...

Is there any HTML code that is able to implement a currency format identical to the one we've customized in Google Sheets/Google Apps Script

I am currently working with a Google Sheet table that consists of 2 columns. The second column contains charges which can vary based on user input through a Google Form and are summed up using GAS. To view an example, click here. The data from this Googl ...

unable to display data through the web service

The functionality of this code is correct, but it seems to not be displaying records. When the record is retrieved from the file and shown in an alert, everything works fine. $j().ready(function(){ var result =$j.ajax({ ...

"Unlocking the potential of AngularJS: A guide to accessing multiple controllers

I am trying to set a variable in one instance of a controller and read it in another. The variable I need to set is within the object vm (so $scope cannot be used). This is the code for the controller: app.controller("AppController", function(){ var ...

Each time a page loads, the react useContext feature is causing the web socket connection to reset

I have integrated websockets into various parts of my nextJS application and need to make sure they are accessible everywhere without resetting the socket connection. Whenever the connection is reset, it loses all the rooms it was connected to, causing iss ...

Sending data from a JSP page to a JavaScript function

I am working on a script that dynamically adds text boxes based on a specific time interval. <script type="text/javascript> $(document).ready(function() { var data = $('#data').val(); var counter = 1; var d = new Date(); va ...

Creating sparse fieldset URL query parameters using JavaScript

Is there a way to send type-related parameters in a sparse fieldset format? I need help constructing the URL below: const page = { limit: 0, offset:10, type: { name: 's', age:'n' } } I attempted to convert the above ...

What is the best way to combine the elements of two arrays within a v-for loop?

Within my code, I have defined two arrays: users and projects. Each array contains unique numbers as IDs. A project can be owned by multiple users, so in the projects array, there is an array of user IDs named ownersId that corresponds to the id of users i ...

Error: It seems like Material UI has updated their export structure and now `makeStyles` is no longer available in the

The export of makeStyles from @mui/material/styles has been deprecated. Despite importing from @mui/styles throughout my project, this error continues to appear. I have already tried removing the node_modules folder and reinstalled, but the issue persis ...

The <select> element in AngularJS 1.5 is showing the dropdown at unexpected moments, but only on iOS 10 devices

From the title, it's evident that this bug is both intriguing and frustrating. The issue lies with a regular select element in an Angular partial containing the following code: <select ng-options="availweek.weekNumber as availweek.weekNumber for a ...

Avoid including newline characters in the string returned from a curl response

I'm facing some challenges in grasping the concept of avoiding interpolation of escape characters in strings, especially those retrieved from a curl response. The data I am receiving looks like this: {"foo":"bar\r\nbaz"} When executing cur ...

How to quickly send data in AngularJS with only one button press

When I have a textarea and press the "Enter" button, data needs to be sent to the server. However, if I quickly press the "Enter" button several times, the "addNewCommentFactory.addComment" function sends multiple requests. Is there a way to send only one ...

Utilize AJAX to accurately capture and handle error codes

Here is a snippet of code that I want to send to my server: $.ajax({ type: 'POST', url: 'post.php', data: { token: '123456', title: 'some title', url: 'http://somedomain.com', data: & ...

Using Next.js to pass fetched data as props to components

I am currently working on integrating a leaflet map into my Next.js project. The map display is already functioning with predefined latitude and longitude in the component. However, I now need to show data retrieved from my API as the longitude and latitu ...

I am looking to generate div elements using JavaScript to avoid the tedious task of individually creating numerous divs

Instead of manually typing out multiple div tags in the HTML, I would like to dynamically generate them using JavaScript and display them on the page. Below is an attempt at achieving this, but it appears to not be functioning correctly. var arr = {}; f ...

What is causing .then() to not wait for the promise to resolve?

I'm currently delving into an Angular project, and I must admit, it's all quite new to me. My confusion lies in the fact that the .then() function doesn't seem to be waiting for the promises to resolve. Could this have something to do with ...

Display a div every 3 seconds with the help of jQuery

I am seeking a solution to display the second div (box2) every 3 seconds. Can anyone help me achieve this using jQuery? <div id="box1" style="background-color:#0000FF"> <h3>This is a heading in a div element</h3> <p>This ...

What is the best way to save a parsed JSON value to a variable in Express?

I am currently utilizing the body-parser module to parse incoming JSON objects within a POST request. My goal is to extract and store a specific value from the JSON data into a variable for later database insertion. Below is a fragment of the code: var h ...