Directive fails to trigger following modification of textarea model

There is a block of text containing newline separators and URLs:

In the first row\n you can Find me at http://www.example.com and also\n at http://stackoverflow.com
.

The goal is to update the values in ng-repeat after clicking the copy button.

This is the HTML structure:

<div ng-controller="myCntrl">
    <textarea ng-model="copy_note_value"></textarea>

    <button data-ng-click="copy()">copy</button>

    <div>
        <p ng-repeat="row in note_value.split('\n') track by $index"
           wm-urlify="row"
           style="display: inline-block;"
            >
        </p>
    </div>
</div>
    

Controller:

app.controller('myCntrl', function ($scope) {

     $scope.note_value = "first row\nFind me at http://www.example.com and also\n at http://stackoverflow.com";

     $scope.copy_note_value = angular.copy($scope.note_value);

    $scope.copy = function(){
      $scope.note_value = angular.copy($scope.copy_note_value);   
    }

});

There is a directive that should take text and return it as urlified text:

app.directive('wmUrlify', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        scope: true,
        link: function (scope, element, attrs) {

            function urlify(text) {
                var urlRegex = /(https?:\/\/[^\s]+)/g;
                return text.replace(urlRegex, function (url) {
                    return '<a href="' + url + '" target="_blank">' + url + '</a>';
                })
            }

            var text = $parse(attrs.wmUrlify)(scope);
            var html = urlify(text);
            element[0].inneHtml(html)

        }
    };
}]);

Here is the flow: The user changes the text in the textarea and clicks on the copy button. The expectation is to see the change reflected in the ng-repeat.

It seems to work only when a new line is added without changing the content.

What could be the issue here? Check out this Fiddle for reference.

Answer №1

If you're experiencing issues with your ng-repeat, try taking out the track by $index. Angular interprets this as the change in note_value.split('\n') only occurring when there is a modification in the $index i.e. the array size after being split by new lines.

By default, track by signifies the identity of each item. So adjusting it to track by the $index and not adding any new lines but merely updating existing content might cause Angular to overlook changes.

Update

Deleting the track by $index function may result in an error if there are duplicated values post-split. Instead, consider using a straightforward function like: (declare this in your controller)

$scope.indexFunction = function($index, val) {
    // Generating a unique identifier based on index and value
    return $index + val;
};

Then implement it in your ng-repeat like so:

<p ng-repeat="row in note_value.split('\n') track by indexFunction($index, row)"></p>

https://docs.angularjs.org/api/ng/directive/ngRepeat

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

Resizing nested elements while maintaining consistent padding dimensions

If you're looking to create a sleek foundation for a 200px wide, 30px high editable combobox that can be easily used with angular binding or other JavaScript data-binding solutions, consider the following HTML code. However, there's a desire to m ...

Adjust the quantity of divs shown depending on the value entered in a text input field

It seems like I am on the right track, but there is something simple that I am missing. I'm currently utilizing the jQuery knob plugin to update the input field. $('document').ready(function() { $(".knob").knob({ c ...

Using JavaScript and HTML to show the current month, date, and year on a webpage

I am looking to display not only the time, but also the month, date and year. My attempted solution involved creating variables for the month, day and year, and then using getElementById. Here is an example of what I tried: var d = date.getDay(); var mn ...

How is it possible that this React setter is effectively working despite the fact that it is within a stale closure

I've come across this interesting function that I need help understanding. The randomize function seems to be consistent in its behavior despite multiple renders, thanks to being wrapped in a useCallback. Each time the randomize button is clicked, it ...

Tips for dynamically creating column headings and table values using JSON arrays in AngularJS

On a web page, there are two radio buttons that produce different results: The first button shows Student Details and the corresponding JSON array is as follows : [{"Name":"A", "Class":"x", "Section":"abcd", "DOB": "XYZ"}, {"Name":"B", "Class":"x", "S ...

What is the best way to show an error message in AngularJS if passwords do not match?

I recently started learning Angularjs and I'm struggling with displaying an error message when the password doesn't match the confirm password. Can anyone provide some guidance? I'm still new to programming so any help is appreciated. Thank ...

Stopping the interval in Vue before the component is destroyed

I am currently facing an issue with a countdown timer implemented on a component. The timer functions properly, however, I want it to stop counting down once the user navigates away from the page where the component is located. I have attempted to use cl ...

Retrieving the response value in AngularJS with $resource

I'm trying to retrieve the response of a request using $resource in AngularJS. Here is an example implementation: angular.module('app').factory('AuthResource', ['$resource', function($resource) { return { isA ...

Converting JSON to Array: A Step-by-Step Guide

Greetings, StackOverflow community! This is my inaugural question here. I believe the answer is not overly complex, but my knowledge of Javascript is quite rudimentary. Currently, I have a JQuery AJAX function that processes this JSON object: { "Users" ...

I am encountering challenges with React.js implemented in Typescript

Currently, I'm grappling with a challenge while establishing a design system in ReactJS utilizing TypeScript. The issue at hand pertains to correctly passing and returning types for my components. To address this, here are the steps I've taken so ...

AngularJS encountering unresponsive resources

When setting up my Angular App, I include various resources like this: angular.module('myApp', ['infinite-scroll', 'chieffancypants.loadingBar', 'ngResource']) Next, in the html file: <script type="text/javascr ...

The solution to enabling multiple inputs when multiple buttons are chosen

Below is a link to my jsfiddle application: http://jsfiddle.net/ybZvv/5/ Upon opening the jsfiddle, you will notice a top control panel with "Answer" buttons. Additionally, there are letter buttons, as well as "True" and "False" buttons. The functionali ...

Display HTML instead of text in print mode

Hello, I need help with printing HTML code, specifically an iframe. When I try to add my HTML iframe code, it only prints as plain text. I want to be able to see the actual iframe with its content displayed. Thank you. <script> const messages = [&apo ...

After running the `npm run build` command in a Svelte (not Svelte Kit) application, the index.html file displays as

When I run the npm run dev server, it displays the default counter app that is built. However, if I build a plain HTML, CSS, and JavaScript project using npm run build in the dist folder, then open the index.html file, it shows a blank page even though the ...

Navigating through events within React

I'm working on creating a login page, where upon clicking the submit button it should navigate to the Dashboard page. However, I seem to be encountering an issue with my code. After entering login details and clicking on the login button, the details ...

The NPM command fails to execute the Webpack script, yet it successfully runs when manually entered into the terminal

Working on my project with Electron-React-Boilerplate, I encountered an issue while running npm run build-renderer. Despite the script appearing to finish, I receive an error. If I manually enter the code related to the build-renderer script in the termin ...

Looking for the final entry in a table using AngularJS

Hey everyone, I'm dealing with a table row situation here <tbody> <tr *ngFor="let data of List | paginate : { itemsPerPage: 10, currentPage: p }; let i = index"> <td>{{ d ...

"Error encountered: Route class unable to reach local function in TypeScript Express application" #codingissues

Experiencing an 'undefined' error for the 'loglogMePleasePlease' function in the code snippet below. Requesting assistance to resolve this issue. TypeError: Cannot read property 'logMePleasePlease' of undefined This error ...

Ways to avoid data looping in jQuery Ajax requests

This is in relation to the assignment of multiple users using the Select2 plugin, Ajax, and API. The situation involves a function that contains 2 Ajax calls with different URLs. Currently, there are pre-selected users stored in the database. The selection ...

Preview multiple images while uploading in a React JS application

In order to achieve multiple image upload with preview using React JS, I attempted the code below. However, I encountered an error in the console: Uncaught DOMException: Failed to set the 'value' property on 'HTMLInputElement': This ...