Adjusting the content within a text area using an AngularJS service

I am currently editing text in a textarea within the admin view and I would like to display it through an angular service on the user view. However, I want the text to be displayed in multiple rows, maintaining the same format that I entered in the textarea. This textarea and button are located in the admin view

 <textarea name="" id="textAreaAbout" cols="50" rows="10" ng-model="aboutAdmin.about"></textarea>
 <button type="button" class="btn-primary" ng-click="aboutAdmin.saveAboutBtn(aboutAdmin.about)">Save</button>

service

app.factory('global', function(){

    let _items = [
        'Hi, my name is Pavlo Lapan and I am front-end developer from Ukraine.',
        'I have got more than 1 years of experience in web development. I think my strong points are dedication, punctuality and easy in communication',
        'Right now I am on the third year of studying at Software Engineering specialization in Lviv National University, in Ukraine.',
        'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci architecto aspernatur, distinctio doloribus error et maxime tempore? Ducimus, exercitationem sed.',
        'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci architecto aspernatur, distinctio doloribus error et maxime tempore? Ducimus, exercitationem sed.',
        'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci architecto aspernatur, distinctio doloribus error et maxime tempore? Ducimus, exercitationem sed.',
        'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci architecto aspernatur, distinctio doloribus error et maxime tempore? Ducimus, exercitationem sed.'
    ];

    let _itemId = 1;

    return {
        getItems: function(){
            return _items;
        },
        getItemId: function(){
            return _itemId;
        },
        setItemId: function(itemId){
            if(itemId<_itemId) alert('error')
            else _itemId = itemId;
        },
        setItems: function (items) {
            _items = items;
        }
    }
})

controller

app.controller('aboutAdminCtrl', function(global){
    let vm = this;
    vm.about = global.getItems();

    vm.saveAboutBtn = function (text) {
        console.log(vm.about);
        vm.about = text;
        console.log(vm.about);
        global.setItems(vm.about);
    }
})

user view

<p ng-repeat="text in about.about track by $index">{{text}}</p>

User Controller

app.controller('aboutCtrl', function(global){
    let vm = this;
    vm.about =[];
    vm.about = global.getItems();
})

Answer №1

Your issue arose from the use of a string: 'line1\n;line2\netc...' instead of ['line1', 'line2', 'etc...']

It's important to note that in Javascript, a string can be seen as an array of individual characters; for example, ['l', 'i', 'n', 'e', '1', '\n', ...]. By iterating over single characters using ng-repeat, you encountered this problem.

To resolve this issue, you need to include some conversion:

app.controller('aboutAdminCtrl', function(global){
    let vm = this;
    vm.about = global.getItems();

    vm.saveAboutBtn = function (text) {
        const separateLines = text.split('\n');
        global.setItems(separateLines);
        vm.about = global.getItems(); //Assuming a list of separate lines is suitable here
        console.log(vm.about);
    }
})

UPDATE

I also overlooked an essential aspect. You must have a separate model field for textarea because the textarea itself requires plain text format like 'line\nline2\n...', while ng-repeat works with an array of lines. The ideal solution would involve moving the conversions into additional getter and setter methods within the global service.

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

Next JS encountered an error - Error [ERR_HTTP_HEADERS_SENT]: It is not possible to set headers after they have already been sent to the

Having crafted a serverless application using next.js, Vercel, and Google Sheets to store customer contact data, I encountered an issue post-deployment. While my application works flawlessly locally, after deployment, I started receiving the following erro ...

Incorporating groovy script into HTML: Is it possible, akin to embedding JavaScript

Can groovy script be embedded in HTML similar to JavaScript? I am interested in creating an onclick button event that utilizes groovy script instead of JavaScript. Thank you. ...

Having trouble getting the .replace() Javascript function to work on mobile devices?

I have a code snippet for implementing Google Analytics. Here it is: $(function () { $('.plan-choose-btn a').bind('click', function(e) { //ga load image <% String myaccGAEventUrl = trackGoogleAnalyticsEvent(requ ...

Display tables side by side using Material-UI

Presently, I am utilizing NextJs and MaterialUI to display a table with data fetched from an API created in Strapi. Challenge The current issue lies in using a table component with props that are imported into a page, where the props are mapped to an API ...

How to incorporate the angular-qr-scanner bower component into your Meteor project

Currently, I am attempting to integrate the Angular QR Scanner into my Meteor application. It seems that the only available method for installation is through Bower, however, it appears that Meteor's support for bower has been deprecated since version ...

Submitting form data in Angular is a straightforward process

I'm currently using the ng-flow library to upload images to my server. After a user drags and drops an image, I can successfully retrieve the HTML 5 file image in my controller. However, when trying to download it to the server along with other parame ...

using javascript to retrieve php variables

After creating a webpage, setting up Apache2 on an Ubuntu server to access it over the internet, and installing PHP5 and MySQL, I encountered issues with accessing database information on my page through a .php file. Despite having a file named test.php th ...

Stop jQuery function from activating twice during scrolling

I'm looking for a solution to optimize my code that detects if an element is in the viewport and triggers certain actions. Currently, it re-runs the code every time a scroll event occurs when the element is above the fold. Is there a way to make it on ...

Creating an array of multiple divs based on numerical input

I am working on a project to show multiple divs based on the user's input number. For example, if the user selects 3, then 3 divs should be displayed. While I have successfully implemented this functionality, I need to dynamically assign IDs to each ...

Achieve automated zooming out using highcharts-ng through code

Currently, I am using Highcharts-ng as seen on https://github.com/pablojim/highcharts-ng Upon inspecting the source code, I have noticed some interesting functionalities in the directive utilizing scope.$on which I can leverage for broadcasting. One examp ...

Achieving asynchronous results in the parent function with TypeScript: a guide

The code structure provided is as follows: import {socket} from './socket'; class A{ Execute(...args[]){ //logic with Promises SomeAsyncMethod1().then(fulfilled1); function fulfilled1(){ SomeAsyncMethod2(args).then(fulfilled2); ...

Struggling with setting up a PHP and Ajax registration and login system

Struggling with my code and in need of assistance. Desperately trying to set up a register form where users can input their username and password to sign up. Planning to utilize ajax, however, the integration seems faulty. For testing purposes, I tried ech ...

Saving iFrame as Image using Codemirror and html2canvas

Here are a few experiments I conducted with html2canvas: Fiddle 1 (Using html2canvas): Fiddle 2 (Using html2canvas without Codemirror): Fiddle 3 (Using html2canvas with Codemirror): Fiddle 4 (Using html2canvas with Codemirror): I recently wante ...

Troubleshooting: Issues with Custom Image Loader in Next.js Export

I'm encountering a problem while attempting to build and export my Next.JS project. The issue lies with Image Optimization error during the export process. To address this, I have developed a custom loader by creating a file /services/imageLoader.js ...

What is the best way to incorporate external HTML content while ensuring HTML5 compatibility? Exploring the different approaches of using PHP, HTML

While this may seem like a simple task to the experts out there, I have been struggling for over an hour without success... My objective is to use a single footer file and menu file for all my webpages while considering blocking, speed, and other factors. ...

Retrieve the element located within a "block" element that is relative to the user's click event, without the

I'm pondering whether it's feasible, but here's my concept: Within my page, there are multiple identical blocks with the same classes, differing only in content. I am unable or unwilling to assign IDs because these blocks are dynamically g ...

`Gradient blending in ChartJS`

Currently, I am facing an issue with my line chart having 2 datasets filled with gradients that overlap, causing a significant color change in the 'bottom' dataset. Check out my Codepen for reference: https://codepen.io/SimeriaIonut/pen/ydjdLz ...

Verifying the format of an object received from an HTTP service using a TypeScript interface

Ensuring that the structure of the http JSON response aligns with a typescript interface/type is crucial for our javascript integration tests against the backend. Take, for example, our CurrentUser interface: export interface CurrentUser { id: number; ...

Ways to reset the selected option when the user chooses a different option using either Jquery or Vanilla JavaScript

I am currently working on a functionality to clear the select option when a different brand is selected. The issue I am facing is that when I choose another brand, the models from the previous selection are not cleared out. For example, if I select BMW, I ...

Tips for managing mouse over events in legends on highcharts

I have successfully implemented mouseover/mouseout event handling for donut slices. Please review my code below: http://jsfiddle.net/nyhmdtb8/6/ Currently, when I hover over a slice, it highlights that slice and greys out all others. Is it possible to ac ...