Clickable elements are not functioning on dynamically generated divs

In the process of developing an application using Angular, I encountered a scenario where I needed to fetch and display data from a web service. The challenge was in dynamically creating div elements with the retrieved data:

for(var i = 0 ; i < data.Output.length ; i++){   
          var listItem = document.createElement("div");
           listItem.setAttribute("ng-click","doMove()");
          listItem.className = "list-item";
          var name = document.createElement("span");
          name.className = "name"
          name.appendChild(document.createTextNode(data.Output[i].name));
          var link = document.createElement("a");
          link.appendChild(document.createTextNode('›'));


          listItem.appendChild(name);
          listItem.appendChild(link);
        wrapper.appendChild(listItem);
        }

However, I discovered that clicking on these dynamically created divs did not trigger the intended function.

UPDATE: It's worth noting that the data being fetched is through an HTTP request.

UPDATE 2: These dynamic div elements are appended into the following container:

     <div id = "wrapper">
--->
     </div>

To retrieve the data within the controller, I use the following approach:

var request = $http({
        method: "post",
        url: url",
        data: data,

        headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }
        });

        request.success(function (data) {

        });

Answer №1

If you want to tackle this problem in a more structured way, consider using ng-repeat. Alternatively, if you're facing challenges working with JavaScript, creating a directive may be the solution. To incorporate Angular features into dynamically generated DOM elements for a directive, utilize the $compile service.

Example of ng-repeat:

<div ng-repeat="item in data.output">
    <div class="list-item" ng-click="doMove()">
        <span>...</span>
    </div>
</div>

In the case of a directive approach, within your link function, you can apply the same principle by integrating the service as follows:

function linkFunc($scope, elem, attrs){

     //Remember to include the $compile service in your directive
     $compile( elem )( $scope )

}

Answer №2

Implement this feature with ng-repeat. Assuming you are utilizing $scope and not controller as:

<div ng-repeat="d in data.Output" ng-show="data" ng-click="doMove()">
    <span>{{d.name}}</span>
</div>

You can control the visibility of the divs by using ng-show="data" only if data is defined. Set it to be default false, null, or undefined.

Answer №3

Check out this Plunkr I created for you: http://plnkr.co/edit/S5Ch8yGS1eNabJ0SWgBx?p=preview

angular.module('plunker', []);

angular.module('plunker')
  .component('list', {
    controller: 'ListController',
    templateUrl: 'list.html'
  })
  .controller('ListController', function() {
    this.listItems = [
      { name: 'item 1', value: 'Description to describe the item.' },
      { name: 'item 2', value: 'Description to describe the item.' },
      { name: 'item 3', value: 'Description to describe the item.' },
      { name: 'item 4', value: 'Description to describe the item.' },
      { name: 'item 5', value: 'Description to describe the item.' }
    ];
  });
<ul class="list">
  <!-- When using a Component, the controllers alias is "$ctrl" by default. -->
  <li ng-repeat="item in $ctrl.listItems">
    <strong>{{ item.name }}</strong>
    {{ item.value }}
  </li>
</ul>

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

Error: Kinetic.js cannot upload image to canvas

There must be something simple that I'm missing here. I've checked my code line by line, but for some reason, the image just won't load. var displayImage = function(){ var stage = new Kinetic.Stage("imgarea", 250, 256); var layer = new ...

Add the item to a fresh array using the Ajax function

Here is an array that I have: var arrayOfResults = []; // Results after like statement After making a database call, I receive a JSON result like this: [{ "id": "{fcb42c9c-3617-4048-b2a0-2600775a4c34}", "pid": "{34214CCB-90C3-4D ...

Choosing a specific column in an HTML table using jQuery based on the text within it

I have a table with a similar structure as shown below: <table> <c:forEach ...> <tr> <td>test</td> // this is the initial value <td>random value</td> <td>random value</td&g ...

Tips for resolving the "Page Not Found" error in your NextJs application

I am organizing my files in the following structure src/ ├── app/ │ ├── pages/ │ │ ├── authentication/ │ │ │ ├── SignUp/ │ │ │ │ └── page.tsx │ │ │ └── SignIn/ │ ...

Utilize angular to call a function when navigating

Having an issue with ChartJS while creating a chart using angular. The problem arises when navigating to a new page and then back to the original one, as the JavaScript is not triggered again. Is there a way to automatically invoke a JavaScript function o ...

typescriptWhat is the syntax in TypeScript for creating a prototype of a multidimensional

I'm currently working on implementing additional methods for a 2D array using TypeScript. Adding methods to a 1D array is straightforward, as shown below: interface Array<T> { randomize(); } Array.prototype.randomize = function () { ...

Dynamic text displayed on an image with hover effect using JavaScript

Currently, I am in the process of developing a website for a coding course that is part of my university curriculum. The project specifications require the use of JavaScript, so I have incorporated it to display text over images when they are hovered over ...

Wrap the words around to fit a rectangle with a specific ratio, rather than a specific size

Does anyone have a solution for breaking text at word boundaries to perfectly fit a rectangle with a specific approximate ratio, such as 60:40 (width:height)? Please note that this is not just about setting a width limit (e.g. 80 characters or 600px) and ...

Incorporate JSON when adding a new row to the database using Ruby On Rails

Greetings, fellow developers! I am currently working on an application with a backend in Rails. My goal is to create a user from an AJAX request and have the server return a JSON object containing the newly saved user information. Below is my Rails code s ...

Troubleshooting issue with file upload feature in Angular for Internet Explorer 9

I have implemented a file upload method using the following code: <input type="file" name="upload-file" ng-model= "excelFile" accept=".xlsx" onchange="angular.element(this).scope().fileChanged(this);" ...

Designing a sequential bar graph to visualize intricate data using AmCharts

I received the following response from the server in JSON format: [{ "data1": { "name": "Test1", "count": 0, "amount": 0, "amtData": [ 0,0,0,0 ], "cntData": [ 0,0,0,0 ], "color": "#FF0F00" }, "data2": { ...

Angular's getter value triggers the ExpressionChangedAfterItHasBeenCheckedError

I'm encountering the ExpressionChangedAfterItHasBeenCheckedError due to my getter function, selectedRows, in my component. public get selectedRows() { if (this.gridApi) { return this.gridApi.getSelectedRows(); } else { return null; } } ...

Error: TypeScript Knockout table failing to display data

I have a table that displays invoices, along with a nested table showing the individual checks associated with each invoice. I am using knockout and typescript to render these tables. Currently, I can successfully display the invoices but am facing difficu ...

Dealing with audio bleed from a previous recording using fluent-ffmpeg

const Discord = require('discord.js'); const client = new Discord.Client(); const ffmpegInstaller = require('@ffmpeg-installer/ffmpeg'); const ffmpeg = require('fluent-ffmpeg'); ffmpeg.setFfmpegPath(ffmpegInstaller.path); co ...

Troubleshooting MongoDB aggregate lookup failure when using multiple parameters

In my data retrieval process from the comments table, everything is functioning properly. However, I am aiming to optimize performance by performing a join equivalent on the users collection to fetch additional user details associated with each comment. B ...

Localization of date picker in material-table(Material UI)

Does anyone have experience with localizing the date picker in material-table (Material UI)? The date picker is specifically used for filtering in this scenario. import React from 'react'; import MaterialTable from 'material-table'; fu ...

Changing return values with Jest mocks in TypeScript

Here I am again with a very straightforward example. In summary, I require a different response from the mocked class. Below is my basic class that returns an object: class Producer { hello() { return { ...

Using ExpressJS and Jade to submit a form using the POST method and redirecting to a specified path

I am exploring node, express and jade for the first time and working on a small application that requires users to enter their name and password in a form. The app then redirects them to a path based on their username. Here is the code snippet to achieve ...

When attempting to use dynamic imports with `react-icons`, NextJS will import all necessary components and dependencies

My current task involves incorporating an Icon from the react-icons package into my project. However, when I attempt to do so using an import statement, the resulting bundle size looks like this: Route (pages) Size First Lo ...

Exploring JavaScript capabilities with Google - managing and updating object names with numbers

After importing JSON data into Google Scripts, I am able to access various objects using the code snippet below: var doc = Utilities.jsonParse(txt); For most objects, I can easily retrieve specific properties like this... var date = doc.data1.dateTime; ...