Using AngularJS, rearrange the text in a text area

Here is a textarea with some content displayed:

<textarea id="textfield"><img src="smile.png alt=":)"/>Hi</textarea>

I have implemented this JavaScript code snippet to extract the img alt value and the text Hi from the textarea in order to rearrange them as :) Hi. However, my goal is to arrange them in the reverse order like Hi :), using the following snippet:

$scope.performaction = function () {
//get the value of the textarea
        var textarea = angular.element('#textfield').val();
        textareaValue = textarea;
        var altValues = [];
    while (true) {
        var altValueMatch = textareaValue.match(/\<img.*?alt=(\"|\')(.*?)\1.*?\>/),
            altValue = (Array.isArray(altValueMatch) && typeof altValueMatch[2] === "string")
                ? altValueMatch[2]
                : null;

        if (altValue !== null) {
            altValues.push(altValue);
        } else {
            break;
        }
        textareaValue = textareaValue.replace(/\<img.*?\>/, "").trim();
    }
var concatenated = [altValues, textareaValue].join(" ");
                concatenated.replace(/&nbsp;|,/g,'');
    //assign the value to the second textarea of ng-model="content"
                $scope.content = concatenated;

            };

I need help in modifying the above JavaScript code so that the retrieved textarea value can be rearranged to display as Hi :) after processing it with AngularJS. Basically, I want the image alt value to appear last.

Answer №1

If you want to keep an eye on the changes of the alt attribute within a directive, here is how you can do it:

JavaScript:

app.directive('altChange',function(){
      return {
        restrict: 'a',
        link: function(scope,elem,attr){
           scope.$watch(function(){return elem.val()},function(value){
              var textarea = value;
        textareaValue = textarea;
        var altValues = [];
    while (true) {
        var altValueMatch = textareaValue.match(/\<img.*?alt=(\"|\')(.*?)\1.*?\>/),
            altValue = (Array.isArray(altValueMatch) && typeof altValueMatch[2] === "string")
                ? altValueMatch[2]
                : null;

        if (altValue !== null) {
            altValues.push(altValue);
        } else {
            break;
        }
        textareaValue = textareaValue.replace(/\<img.*?\>/, "").trim();
    }
var concatenated = [altValues, textareaValue].join(" ");
                concatenated.replace(/&nbsp;|,/g,'');
    //assign the value to the second textarea of ng-model="content"
                $scope.content = concatenated;
           })
        }
      }
    })

HTML:

<textarea alt-change id="textfield"><img src="smile.png alt=":)"/>Hi</textarea>

Explanation

By creating a directive that monitors the element's value changes, whenever the value is updated, the Angular digest system will trigger the function passed to the $watch function.

It's worth noting that the default scope property is set to scope:false, so the $scope.content will bubble up to your controller's $scope.

Answer №2

To optimize your JavaScript code, consider rearranging the concatenation sequence to prioritize textarea value before alternating values.

var combinedText = [textareaValue, alternateValues].join(" ");
combinedText.replace(/&nbsp;|,/g,'');
//Set the modified value as the content for the second textarea with ng-model="content"
$scope.content = combinedText;

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

What is the most effective way to set userForm.$dirty to true in AngularJS?

I am trying to set the dirty value of a form to true using $scope.userForm.$dirty = true; However, it does not seem to be working. Can someone please assist me with this issue? Thank you. ...

Customizing the title in Firebase-UI: Simple steps to override it

Currently, I am utilizing firebase with firebaseui to log into my React app. <StyledFirebaseAuth uiConfig={uiConfig} firebaseAuth={firebase.auth()} /> However, I have encountered an issue where I am unable to override the default Title (Sign in with ...

The error message "Attempting to send a message using an undefined 'send' property in the welcomeChannel" is displayed

bot.on('guildMemberAdd', (member) => { console.log(member) const welcomeChannel = member.guild.channels.cache.find(channel => channel.name === 'welcome'); //const channelId = '789052445485563935' // welcome c ...

The Angular user interface typeahead feature fails to automatically fill in the text box when an option is

Utilizing the Angular UI typeahead directive has been quite helpful for me. I am working with a list of individuals in the typeahead dropbox, where each person is represented as an object with details like LastName, FirstName, CustomerNumber, and more. Des ...

Ensure that the Get Request retrieves a value in a string format and store it in a designated

Below are the methods I have implemented: function RequestGet(options, url){ fetch(url, options).then(function(response){ return response.json(); }).then(function(value) { data = JSON.stringify(value) console.log(data) } ...

true not redirecting to 404 page when axios request fails

I have implemented Axios to access a basic API. My goal is to direct the user to the default Next.js 404 page in case of a failed request with a 404 error code. I have set the notFound boolean to true if the request status is 404. There are a total of 10 u ...

A bug encountered with AngularJS and dojox.charting: Error message 'nodeType' of null

My goal is to dynamically populate a div with various graphs from Dojo, depending on the current data model. However, I keep encountering the error message "Cannot read property 'nodeType' of null" when running my code. I suspect that this issu ...

Creating an array with user-selected objects in IONIC 3

I've been attempting to separate the selected array provided by the user, but unfortunately, I'm having trouble isolating the individual elements. They are all just jumbled together. My goal is to organize it in a format similar to the image lin ...

What is the process for redirecting an API response to Next.js 13?

Previously, I successfully piped the response of another API call to a Next.js API response like this: export default async function (req, res) { // prevent same site/ obfuscate original API // some logic here fetch(req.body.url).then(r => ...

Issues with navigation drawer not functioning

function adjustMenu() { var navigation = document.getElementById("myTopnav"); if (navigation.className === "topnav") { navigation.className += " responsive"; } else { navigation.className = "topnav"; } } body {margin:0;} ul ...

Dynamic manipulation of classes based on user attributes

One thing I've noticed is that certain WordPress themes, like 'Thematic', include user-specific classes in the body element to avoid using CSS browser hacks. For example: wordpress y2010 m02 d26 h05 home singular slug-home page pageid-94 pa ...

Implementing a Context Menu with a Single Click

I need assistance with creating a context menu that appears when the user clicks inside an HTML5 canvas. I want to have functions called when an item in the menu is selected. Can anyone provide guidance on how to achieve this? ...

Create a line connecting two divs using jQuery's DOM manipulation capabilities

Looking to connect two divs with a straight line, I stumbled upon jQuery DOM line, which appears to offer a more streamlined solution compared to jsPlump. I attempted to incorporate it into my code, but unfortunately, it's not working as expected. Be ...

What is the process for using populate with a custom ObjectId that is of type String?

My current setup involves using a firebase project for authentication and saving additional user information in MongoDB. The challenge comes in when assigning the UID of the firebase user to the _id field of the user model in MongoDB. To make this possible ...

A guide to handling errors and switching between src images in Angular with Javascript

I've been developing a complex Angular application and I'm facing an issue with switching between different images when errors occur. Here is the code snippet I am currently working with: <picture> <source [srcset]= ...

What is the best way to determine if a value exists in a JSON response?

I am currently creating a test in Postman to verify if a JSON response contains the 'RegressieMapTest' Label. Here is my script: pm.test("Is the folder created correctly?", function(){ var jsonData = pm.response.json(); var objString = ...

Interactive website with no client-side URL management

I'm facing a challenge that I just can't seem to figure out. I've developed a website using node.js and have successfully written all the necessary code for routing, including routing for sub-domains. Some sections of the site are only acces ...

Exploring the power of Mongoose.js and using the query object with Regular Expressions

In an application focused on locomotives, the search functionality queries models with specific metadata. To check against the keywords field, I need to include a regexp engine. My current approach is as follows: this.keywords = strings.makeSafe(this.par ...

Only the initial upload file is being passed through the Apollo Express server, with the remaining files missing in action

Currently, I am utilizing the apollo-express server with GraphQL. One issue I am encountering involves a mutation where I pass files from the front-end to the back-end. Strangely, I receive the file:{} object only for the first file - for the others, I rec ...

Is there a way to prevent camera motion in three.js when the escape key and directional keys are activated?

While working on my project with Pointer Lock Controls, I came across a bug. When the player is pressing any directional keys on the keyboard and simultaneously presses the escape button to turn off the Pointer Lock Controls, the camera continues to move ...