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

Gather data from various textboxes and combine them into a unified string with the help of JavaScript

I am currently facing a challenge where I need to extract the values from multiple textboxes and combine them into a single string. This string will then be sent to my PHP processing page for insertion into a database table. The textboxes mentioned above ...

Tips for adding a new value to an array of objects in React

As I navigate my way through the world of React as a newcomer, I've encountered a challenge that I need some advice on. I am attempting to add a new key and value to an array of objects, but I'm struggling to accomplish this task. Can anyone prov ...

Problem Installing Express Sharp using Docker

When deploying via Docker, I encountered an error with sharp, even though it works fine on my workspace. I followed all the steps but still faced issues. Error: 'linux-x64' binaries cannot be used on the 'linuxmusl-x64' platform. P ...

Running Node.js code from npm within Swift can be achieved by following these steps:

I am looking to integrate a Node JS package downloaded from npm into my Cocoa App and run it using Swift. Despite searching online, I have not been able to find any information on whether it is possible to call an npm package from Swift. Can anyone help m ...

Guide to forming an array by extracting specific properties from a nested JSON array using javascript

Currently, I have this list: list = { id: 1, arr: [ {index : 1 , description: "lol" , author: "Arthur"}, {index : 2 , description: "sdadsa" , author: "Bob"}, {index : 3 , desc ...

Looping through elements using .each in jQuery and accessing their values in the following iteration

Here is the code snippet I've been working on: var index=0; var load=0; $("td.load_ads").each(function(){ var loading=$(this); $.post('/self_coded_helpers/jpost_get_ads.php',{index:index,type:'fetch_id' ...

Error found in Paper.js at line 81: Uncaught TypeError - Unable to access properties of undefined (specifically '1') while utilizing Material UI and Joy UI

I am encountering an issue while using react js with material UI and JoyUI, where I am getting a blank screen. Below is the code snippet causing the problem: import React from 'react'; import { CssVarsProvider } from '@mui/joy/styles'; ...

Angular repeatedly executes the controller multiple times

I have been working on developing a chat web app that functions as a single page application. To achieve this, I have integrated Angular Router for routing purposes and socket-io for message transmission from client to server. The navigation between routes ...

Access Denied - NodeJS

Currently facing an issue with my MEAN stack application on AWS - Windows. I've set port 3000 for the Node server and IIS is using the default port 80. When trying to retrieve data using Angular via Node, I encounter an error while making a GET reque ...

The ngOnInit function is not triggered upon instantiation of an Injectable class

What could be causing the ngOnInit() method not to be called upon resolution of an Injectable class? Code import {Injectable, OnInit} from 'angular2/core'; import { RestApiService, RestRequest } from './rest-api.service'; @Injectable ...

Looking for a way to limit the number of characters allowed per line in a textarea using jQuery

I have the following HTML textarea: <textarea name="splitRepComments" cols="20" rows="3" ></textarea> I have implemented a maxlength restriction using jQuery with the following function: var max = 100; $('#splitRepComments').bind(" ...

Unable to alphabetically arrange buttons automatically

I am encountering a challenge with automatically sorting buttons alphabetically on my webpage. I am unable to determine the method for sorting these buttons using jquery or javascript, but my goal is to have them sorted automatically when the page loads. I ...

The slideshow fails to show correctly after being loaded from an external JavaScript file

Utilizing standard code, I have set up a Slideshow at the top of a website: HTML: <body id="Top" onload="showSlides()"> ... <div id="slides"> <div id="slide1" class="slides fade"></div> <div id="s ...

Dynamically remove a MongoDB entry with precision

I'm having trouble deleting an entry in MongoDB based on the id variable. Even when I pass the id as a parameter to the method, it doesn't seem to work. I've double-checked the variable inside the method and I'm confident that it has th ...

P2P Wireless Capabilities for WebRTC Video Streaming

I am currently planning to create a demonstration of a wireless technology that enables two computers to connect with each other. For the purpose of this project, let's envision the network as if the two computers were linked by an incredibly long Eth ...

Using JQuery with the latest version of Google Sites is a game-ch

My coding knowledge is very limited, especially beyond VBA. I've hit a roadblock and it seems like I'm overlooking something obvious. What I'm attempting to accomplish: I need this code to be integrated into a New Google Sites page (which h ...

Challenges compiling 'vue-loader' in Webpack caused by '@vue/compiler-sfc' issues

The Challenge Embarking on the development of a new application, we decided to implement a GULP and Webpack pipeline for compiling SCSS, Vue 3, and Typescript files. However, my recent endeavors have been consumed by a perplexing dilemma. Every time I add ...

Need help setting up a time-based query in Laravel? Here's how to schedule it!

I am currently using the following query to update a status value. public function updateStatus(Request $request) { $customer = Customer::findOrFail($request->user_id); $customer->status = $request->status; $customer->new_customer_s ...

The AngularJS directive is failing to run the Jquery-ui menu component

I'm struggling to implement a jquery-ui menu within an AngularJS directive. I attempted to use this fiddle as a reference for my project. html: <div ng-app="myApp" ng-controller="mainController"> <ul j-menu> <li>Test 1</l ...

Postman grants me the cookie, yet Chrome doesn't seem to deliver it

As I attempt to set a cookie named auth, containing the user's ID signed with JWT, I am puzzled by not seeing the auth cookie in Chrome when visiting http://localhost:5000/. Instead, I only observe these two cookies; Interestingly, when accessing the ...