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

Adding jQuery namespace to AngularJS

I'm facing a bit of an issue here. I've implemented RequireJS to manage my modules and dependencies. To prevent cluttering the global namespace, I've set up the following configuration to avoid declaring $ or jQuery globally: require.confi ...

The fixed navigation bar shows a flickering effect while scrolling at a slow pace

Currently facing a challenge with our sticky navigation. Noticing a flickering issue on the second navigation (sticky nav) when users scroll down slowly. The problem seems to be specific to Chrome and Edge, as it doesn't occur on Firefox, IE11, and S ...

Developing Your Own Local Variable in Angular with Custom Structural Directive ngForIn

I am hoping for a clear understanding of this situation. To address the issue, I developed a custom ngForIn directive to extract the keys from an object. It functions correctly with the code provided below: import {Directive, Input, OnChanges, SimpleChan ...

Customize a web template using HTML5, JavaScript, and jQuery, then download it to your local device

I am currently working on developing a website that allows clients to set up certain settings, which can then be written to a file within my project's filesystem rather than their own. This file will then have some parts overwritten and must be saved ...

Tips for efficiently moving through divs in a personalized single page application?

Exploring the world of JS frameworks and single page app functionality is a bit of a mystery to me. Currently, I have a pseudo single page app set up without any specific framework in place. The setup involves 3 tabs that toggle visibility for 3 different ...

What is causing the classList function to throw an error: Uncaught TypeError: Cannot read properties of undefined (reading 'classList')?

There's an error that I can't figure out: Uncaught TypeError: Cannot read properties of undefined (reading 'classList') console.log(slid[numberArray].classList) is working fine, but slid[numberArray].classList.add('active') is ...

The ajax function is malfunctioning when called from an external JavaScript file

I am having an issue with a Registration page that only has UserName and Password fields. When I click on the Submit button, I want to be able to submit the new User Details using an ajax call with jQuery. I have tried defining an Insert function on butt ...

Is there a way to verify HTML binding prior to setting up an AngularJS directive?

On a page where I utilized a custom select-box directive to display the Month, certain arguments are required by the directive: <custom-select-box id="month" model="month" model-required model-name="month" options="month.value ...

Putting AngularJS Directives to the Test with Jest

There seems to be a crucial element missing in my overly simplified angular directive unit test. The directive code looks like this: import * as angular from 'angular' import 'angular-mocks' const app = angular.module('my-app&apo ...

Utilize AngularJS to securely retrieve a zip file through a Spring-powered RESTful web service

AngularJs is still unfamiliar territory for me, and I'm looking to develop code that can download a zip file through a Spring-based RESTful web service upon clicking a 'download' button. The web service functionality is all set up, but I nee ...

What is the solution to fixing the Vue 2 error when using Node 12?

Issue with Node 12: It seems that there is an error related to the node-sass library in Node 12. Error message from Node: node-pre-gyp ERR! node -v v12.1.0 node-pre-gyp ERR! node-pre-gyp -v v0.10.3 node-pre-gyp ERR! not ok ...

Is there a way to append the current path to a link that leads to another URL?

I am currently in the process of separating a website, with the English version being on the subdomain en. and the French version residing on the www. Before making this change, I have a drop-down menu that allows users to select their preferred language ...

Encountered an unhandled runtime error: TypeError - the function destroy is not recognized

While working with Next.js and attempting to create a component, I encountered an Unhandled Runtime Error stating "TypeError: destroy is not a function" when using useEffect. "use client" import { useEffect, useState} from "react"; exp ...

I am interested in incorporating jQuery into my React development project

I'm trying to implement jQuery in React. I have an input field in my project that I am using to create a match event with 'this.state.value'. When the content of the input field matches, I want the borders to turn green and red if they do no ...

Storing JSON information within a variable

I'm currently working on an autocomplete form that automatically populates the location field based on the user's zipcode. Below is the code snippet I've written to retrieve a JSON object containing location information using the provided zi ...

Click to execute instantly without encountering any errors

I'm working with a modal in React JS and I want to trigger a function when the modal opens. I currently have a button function that is functioning correctly using the following code: <button onClick={functionExample("stringParam", true)} ...

Display or conceal various content within div elements using multiple buttons

I have a set of 5 image buttons, each meant to trigger different content within a div. When the page loads, there should be default content displayed in the div that gets replaced by the content of the button clicked. The previously displayed content shoul ...

Ways to update the contents of an individual div within an ng-repeat loop

I am currently working on some Angular code. <div ng-repeat="item in items | filter:search" class="container"> <h3>{{item.name}}</h3> <p>category:{{item.category}}</p> <p>price:INR {{ ...

Using Javascript libraries on a Chromebook: A comprehensive guide to getting started

Doing some coding on my chromebook and wondering if it's possible to download and utilize libraries such as jQuery. Would really appreciate any assistance with this! ...

In the world of Node.js and Java, the concepts of "if"

Here is a code snippet that I am working with: var randFriend = friendList[Math.floor(Math.random() * friendList.length)]; if (randFriend == admin) { //Do something here } else if (randFriend != admin) { client.removeFriend(randFriend); } I am tr ...