Splitting a string in Angular.JS using ng-repeat

Just diving into the world of Angular.JS and grappling with the concept of implementing ng-repeat.

Within my scope, I have a data object derived from JSON fetched from my database. Among the returned 'fields', one particular field can either be a single string or an array.

For instance:

Email Address = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="117c7451657462653f727e7c">[email protected]</a>" or
Email Address = ["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e333b6f1e2a3b2d2a703d3133">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="670a025527130214134904080a">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6d00085e2d19081e19430e0200">[email protected]</a>"]

What I want to achieve is to display whatever content the Email Address field holds within a series of spans. Here is what I've tried so far:

<span ng-repeat="EMAIL_ADDRESS in data.EMAIL_ADDRESS">
    <span>{{EMAIL_ADDRESS}}</span><br />
</span

When Email Address is an array of 3, it displays as intended:

    <span><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e232b7f0e3a2b3d3a602d2123">[email protected]</a></span><br />
    <span><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ee838bdcae9a8b9d9ac08d8183">[email protected]</a></span><br />
    <span><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ee838bddae9a8b9d9ac08d8183">[email protected]</a></span><br /> 

But when Email Address is just a string, it displays like this:

    <span>m</span><br />
    <span>e</span><br />
    <span>@</span><br />
    <span>t</span><br />
    <span>e</span><br />
    <span>s</span><br />
    <span>t</span><br />
    <span>.</span><br />
    <span>c</span><br />
    <span>o</span><br />
    <span>m</span><br />

How can I avoid this scenario? It seems to be related to JavaScript behavior, and I'm unsure how to handle it within Angular.

Answer №1

If you find yourself unable to modify the object retrieved from the database or need to perform this operation on multiple variables, consider creating a function that converts the string into an array. This will prevent your ng-repeat directive from parsing it unnecessarily.

You can create a function directly in your controller like this:

$scope.transformStringToArray = function(objectFromDB) {
    if (!angular.isArray(objectFromDB)) {
        return [objectFromDB];
    } else {
        return objectFromDB;
    }
}

Then simply call the function with your data:

<span ng-repeat="EMAIL_ADDRESS in transformStringToArray(data.EMAIL_ADDRESS)">

Answer №2

If you follow the Angular approach, you would format the data after receiving it. For instance, if the value is a string, replace it with an array containing that value. By doing this, your template will consistently receive results, and your controller logic will manage data structures consistently.

Update: I suggest not directly binding the raw data returned from the server to the $scope. It's beneficial to introduce a level of separation between server data names/types and client data to facilitate future changes without strong coupling.

JavaScript:

$http.get('/my/data').success(function(data) {
  // Data transformation and binding would be done here
  if(angular.isArray(data.EMAIL_ADDRESS)) {
    $scope.emailAddresses = data.EMAIL_ADDRESS;
  else {
    $scope.emailAddresses = [data.EMAIL_ADDRESS];
  }
});

HTML:

<span ng-repeat="emailAddress in emailAddresses">

This approach ensures that your templates are not tightly bound to server API return values/properties.

Answer №3

You have the option to display different cases using separate spans or documents: utilize ngRepeat for arrays and do not use it for simple strings.

It can be structured like this:

<div ng-show="isString(data.EMAIL_ADDRESS)">{{data.EMAIL_ADDRESS}}</div><div ng-hide="isString(data.EMAIL_ADDRESS)" ng-repeat="address in data.EMAIL_ADDRESS">{{address}}</div>

Answer №4

As you retrieve data from the server:

EMAIL_ADDRESS = Array.isArray(EMAIL_ADDRESS) ? EMAIL_ADDRESS : [EMAIL_ADDRESS]

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

Typescript Angular filters stop functioning properly post minification

I developed an angular filter using TypeScript that was functioning properly until I decided to minify the source code. Below is the original filter: module App.Test { export interface IGroupingFilter extends ng.IFilterService { (name:"group ...

Angular JS Touch and Swipe: Interactive Gestures for Enhanced User

Currently venturing into the world of Angular JS as I dive into developing a mobile application. One essential task at hand is creating a service that can manage touch events such as swipe-left, swipe-right, swipe-up, and swipe-down, with corresponding c ...

Connecting Mailchimp with WordPress without using a plugin can lead to a Bad Request 400 error when trying to

I'm attempting to connect with Mailchimp using an Ajax request without relying on a plugin, but I keep encountering a 400 bad request error. The code provided below utilizes vanilla JS for Ajax and the function required for integration with Mailchimp. ...

Issue with updating onclick attribute of popover in Bootstrap 4

My goal is to design a popover in bootstrap 4 with a nested button inside it. However, when I update the data-content attribute of the popover with the button element, the element gets updated but the onclick attribute goes missing. I have experimented wi ...

Injecting multiple instances of an abstract service in Angular can be achieved using the following techniques

I am fairly new to Angular and currently trying to make sense of the code written by a more experienced developer. Please excuse me if I'm not adhering to the standard communication practices and vocabulary. There is an abstract class called abstract ...

The Electron forge project from publisher-github is failing to detect the environment variable GITHUB-TOKEN

I've set up my .env file with the correct token, but I encountered an error when trying to publish my package on GitHub. An unhandled rejection has occurred inside Forge: Error: Please set GITHUB_TOKEN in your environment to access these features at n ...

JSON failing to show all values sent as a string

In a div element there is a table with 3 rows, a textarea, and a button. The JSON data populates the first 3 rows correctly but the textarea remains blank. My goal is to display the previous record from the database in the textarea. function ChangeLoadin ...

How about using jQuery to display information alerts instead of the traditional alert function

Is there a way to display an alert within the login page itself if the login fails, instead of using a popup? error: function(data, status, xhr) { alert("Login failed."); } ...

Utilizing data attributes to configure jQuery plugin settings

Having trouble assigning options to an array value in a jQuery plugin using data attributes. When referencing the data attribute with a class selector: $('.tm-input').tagsManager( { prefilled: $('.tm-input').data('loa ...

Vue.js - Capturing a scroll event within a vuetify v-dialog component

Currently, I am working on a JavaScript project that involves implementing a 'scroll-to-top' button within a Vuetify v-dialog component. The button should only appear after the user has scrolled down by 20px along the y-axis. Within the v-dialog, ...

Using JQuery to swap out background images in CSS

I have been working on a slider that is supposed to fade one picture over another. The issue is that the background change seems to only work in the Dreamweaver preview and not in the actual browser. loop = setInterval(function(){ $("#slider").css("ba ...

Tips for utilizing AJAX to send two values to PHP for comparison

How can I use AJAX to compare two values (#cpassword and #password) to see if they match? I've been attempting it, but it seems like I only get the value of '#cpassword'. Here is my cpassword-check.js file: // Validate confirm password whi ...

Modify the div class depending on the date

I am in the process of creating a simple webpage where I can keep track of all my pending assignments for college. Take a look at the code snippet below: <div class="assignment"> <div class="itemt green">DUE: 28/03/2014</div> </d ...

Attach the Bootstrap-Vue modal to the application's template

I am implementing a custom modal using bootstrap-vue modal in my project on codesandbox. This is the template structure: <template> <b-button variant="link" class="btn-remove" @click="removeItemFromOrder(index)"> Remove item </b-bu ...

Tips for converting an object into parameters for ng-include

What is the best way to create a serialized array of objects that can be used as parameters for ng-include in order to dynamically load data from the server? Using Angular controller and params with requests: app.controller("MyCtrl", function($scope) { ...

How can I dynamically update a div without refreshing the page by using an onclick event on a

When working on my project, I found helpful insights from this Stack Overflow thread. The structure of template-comparison.php involves fetching code from header.php to ensure the page displays properly. However, the actual "fetch code" process remains un ...

Using jQuery to smoothly animate a sliding box horizontally

Is there a way to smoothly slide a div left and right using jQuery animation? I have been trying to achieve this by implementing the code below, which can be found in this fiddle. The issue I am facing is that every time I click on the left or right butto ...

Do we need to use the render method in ReactJs?

I'm curious about how ReactJs uses its Render() functionality. Let's say we have some HTML code within index.html: <section id="Hello"> <h1>Hello world</h1> <p>Something something Darkside</p> </section&g ...

Error: Firebase has encountered a network AuthError, which could be due to a timeout, interrupted connection, or an unreachable host. Please try again later. (auth/network-request-failed

I have set up my Angular app to utilize Firebase's emulators by following the instructions provided in this helpful guide. In my app.module.ts, I made the necessary configurations as shown below: import { USE_EMULATOR as USE_AUTH_EMULATOR } from &apos ...

Experiencing a challenge with Express and PassportJs when using the Google OAuth2.0 strategy as it's not providing the

Currently, I am in the process of configuring an authentication route for our application. Unfortunately, I am facing a challenge with the Google oAuth 2.0 strategy for PassportJs as it does not provide me with a req.user object when using sequelize. Below ...