Press here to remove an element that was generated dynamically within AngularJS

At this moment, any input entered by the user in the text box and then clicked on the button is dynamically displayed inside anchor tags, each in a new line.

Here's the HTML code for the text box and the button:

<input type="text" name="inputText"><br>

<tr>
    <input type="button" value="ADD" ng-click="$ctrl.addtext()">
</tr>

<div id="outputDiv"></div>

Below is the JS function being used:

ctrl.addtext = function () {
    var div = document.getElementById('outputDiv');
    div.innerHTML += "<a href='' style='margin-left:10px'>"+newtext+"</a><br>";
}

Now, is there a way to include a close or remove button (such as an X) at the end of each dynamically generated anchor tag, that when clicked, removes that specific row only?

Answer №1

Custom Edit

Implementing a unique component syntax:

function modifyComponentCtrl ($scope, $compile) {
  
  var ctrl = this;
  ctrl.addtext = function (e) {
    var newtext = document.listForm.inputText.value
    var outputDiv = $('#outputDiv');
    var newRow = $compile("<a href='' style='margin-left:10px'>"+newtext+" - <span ng-click='$ctrl.removeRow($event)'>X</span></a><br>")($scope);
    newRow.appendTo(outputDiv)
  };

  ctrl.removeRow = function(e) {
    e.preventDefault();
    e.target.parentNode.remove();
  };
  
};

 angular.module('consoleApp',[])
   .component('modifyComponent', {
  templateUrl: 'templateId',
  controller: modifyComponentCtrl
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<div ng-app="consoleApp">
  <modify-component></modify-component>  
  
  
  <script type="text/ng-template" id="templateId">
<form name="listForm">
<table border="0" cellspacing="0">
<tr>
<input type="radio" style="margin-left:10px;" name="checkRadio" value="append" checked><span class="add-file-text" style="font-weight:bold;">Add File to Exception List</span><br>
<input type="text" style="width:250px;height:30px;margin-left:10px;margin-top:10px;" name="inputText"><br>
</tr>
<tr>
<input type="button" style="margin-left:10px;margin-top:10px;" value="ADD" ng-click="$ctrl.addtext($event)">
</tr>
<tr>
<td>
<div id="outputDiv"></div>
</td>
</tr>
</table>
</form>
</script>
  
</div>

Revamped Edit - jQuery Syntax and $scope Pass

Include an ng-click and utilize $compile within the controller:

ctrl.addtext = function () {
  var outputDiv = $('#outputDiv');
  var newRow = $compile("<a href='' style='margin-left:10px'>" + 'newtext ' + " <span ng-click='removeRow($event)'>X</span></a><br>")($scope);
  newRow.appendTo(outputDiv)
};

Create a new function

If unsure about the element to remove:

ctrl.removeRow = function(e) {
  e.preventDefault();
  e.target.parentNode.remove();
};

Code Fragment

There might be variations in writing components/controllers.

angular.module('myApp', [])
  .controller('myController', function ($scope, $compile) {

    $scope.addText = function () {
     var outputDiv = $('#outputDiv');
     var newRow = $compile("<a href='' style='margin-left:10px'>" + 'newtext ' + " <span ng-click='removeRow($event)'>X</span></a><br>")($scope);
     newRow.appendTo(outputDiv)
   };
   
   $scope.removeRow = function(e) {
     e.preventDefault();
     e.target.parentNode.remove();
   };


  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
 
  <button ng-click="addText($event)">add text</button>
  
  <div id="outputDiv"></div>
</div>

Answer №2

To capture information of the element clicked, you have options like using the Angular $event property or utilizing an HTML5 data attribute. Here is a basic example of how you can achieve this:

HTML:

<input type="button" value="SEND" ng-click="$ctrl.sendData($event)">

and JavaScript:

ctrl.sendData = function (event) {
    var clickedElement = document.getElementById(event.target.id);
    // Perform actions with the element.
    var outputDiv = document.getElementById('outputDiv');
    outputDiv.innerHTML += "<a href='' style='margin-left:10px'>"+newData+"</a><br>";
}

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 causing my ajax request to malfunction?

I'm encountering an issue while trying to send a request using AJAX. The request is successful when I use the following webservice: https://jsonplaceholder.typicode.com/users However, when I attempt to make the same request with my own service, I fac ...

Concealing a button once the collapse feature is toggled in Bootstrap

The following code snippet from the bootstrap website demonstrates how to use collapse functionality: <a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample"> Link with href & ...

Steps to activate checkbox upon hyperlink visitation

Hey there, I'm having a bit of trouble with enabling my checkbox once the hyperlink has been visited. Despite clicking the link, the checkbox remains disabled. Can anyone provide some guidance on how to get this working correctly? <script src=" ...

Utilizing consistent form elements throughout various tabs

I'm working on an HTML project where I need to replicate form elements across different tabs with each tab having unique values. To achieve this, I found a helpful resource at . Here is what I've attempted: <html> <link rel="stylesheet" ...

Exciting Update: Next.js V13 revalidate not triggering post router.push

Currently using Next.js version 13 for app routing, I've encountered an issue with the revalidate feature not triggering after a router.push call. Within my project, users have the ability to create blog posts on the /blog/create page. Once a post is ...

Button inside a React JS Material UI autocomplete chips component

https://i.sstatic.net/BS4yB.png The image above showcases two input fields with autocomplete functionality. The first field effectively uses chips for autocomplete suggestions. However, the second field features an autocomplete but is non-functional, with ...

What is the best way to create a "tile-based board" for this game?

I am working on a project to create a board made up of tiles, but I am facing difficulty in filling up the entire board area. Currently, I have only managed to create 1 column of the board, as shown in the image. Can someone guide me on how to fill the ent ...

Retrieving data from radio buttons using React Hook Form

As I delve into learning React and Next.js, working with form submissions has been a breeze thanks to react-hook-form. However, I've hit a roadblock when it comes to handling radio buttons in my application. Specifically, there's a step where use ...

What is causing the TouchSwipe jQuery plugin not to function in my code?

I have integrated the TouchSwipe jQuery plugin into my code to detect mouse movement and display the number of pixels moved when swiping left or right. To download the TouchSwipe jQuery plugin, I visited this link: TouchSwipe and then proceeded to use it ...

What could be causing a tooltip to remain visible even after a mouseleave event in a React application

My goal is to display a tooltip when the mouse enters an item, and hide it when the mouse leaves. I created a demo that works perfectly fine. Check out the working demo here The above code successfully shows the tooltip on hover and hides it on leave. I ...

How can you initiate the wizard sequence again in TelegrafJS?

I've created a handler function for "/start" that leads to the wizard scene. Now, I have a message with an inline_keyboard containing a button labeled "redo". When I click on the "redo" button, I want it to restart the entire scene, basically initiat ...

Updating data for a heatmap in Angular-Leaflet

My goal is to display a dynamic heatmap using the Angular-Leaflet directive. I have written the following code: getData().then(function (data) { $scope.heat.index = 0; $scope.heat.data = data; $scope.layers.overlays.heat = { name: "Hea ...

What is the best way to change the state of an Object?

I need to dynamically adjust the internalstatus based on the values of externalValues. If valueOne is true, then I want statusOne to be true. Similarly, if valueTwo is true, I want statusTwo to be true and statusOne to be false. const externalValues = { v ...

Filtering in JavaScript can be efficiently done by checking for multiple values and only including them if they are not

In my current coding challenge, I am attempting to create a filter that considers multiple values and only acts on them if they are not empty. Take the following example: jobsTracked = [ { "company": "Company1", ...

Issue with Vue-Multiselect: Unselecting a group of pre-loaded values is not functioning as expected

My code: https://jsfiddle.net/bgarrison25/tndsmkq1/4/ Html: <div id="app"> <label class="typo__label">Groups</label> <multiselect v-model="value" :options="options" :multiple="true" group-values="libs" g ...

Issue with alert dismissal button not visible

I am dynamically updating the alert message: <div id="alert" hidden="hidden"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> </div> $('#alert').addClass("alert alert-dan ...

Node.js and Express: accessing req.body yields undefined value

In the midst of creating a basic browser application using Express, I encountered an issue when attempting to retrieve the value selected by a user from a dropdown menu. I assigned individual values to each option and set the form method to /post. However, ...

aligning JSON information with JavaScript object

I am currently in the process of setting up a sample dataset in JSON format for a JavaScript tutorial that I'm going through. Here's how the data object looks in JavaScript: app.Book = Backbone.Model.extend({ defaults: { coverImage: ...

The SVG format quickly displays new and larger datasets on line charts without any transition effects

My goal is to create a line chart with animated transitions similar to this demo, but without the dots. I am attempting to integrate this functionality into a react component where the update method can be triggered by another component, allowing the d3 op ...

loop failing to refresh element within array

Is there a way to update a specific property in every element of an array to match its index? I attempted the following approach: static reindexComponentsOnMultiplePages(components) { return components.forEach((el, idx) => (el.componentIndex = id ...