How to dynamically insert elements into the HTML page using Angular

When my page first loads, it looks like this

<body>
 <div class="col-md-12" id="dataPanes">
   <div class="row dataPane"> Chunk of html elements </div>
 </div>

 <div class"col-md-12 text-right">
   <input type="button" class="btn btn-primary" value="Add dynamic row" ng-click="addElementChunk()" />
</body>

I want to add rows to div#dataPanes when the button is clicked
If I were using jQuery, the addElementChunk() function would look like this:

var addElementChunk = function()
{
   var html = "<div class='row dataPane'> Chunk of html elements </div>";
   $("#dataPanes").append(html);
}

How can I achieve the same functionality with Angular?

Answer №1

To achieve this, you must utilize the $compile method.

By utilizing the `$compile` method in AngularJS, you can compile an HTML string or DOM into a template and generate a template function that links the scope with the template.

Also, don't forget about $sce.

`$sce` stands for Strict Contextual Escaping, which is a security feature in AngularJS that restricts bindings to render only trusted values. Its main purpose is to help developers write secure code by default and simplifies the process of auditing for security vulnerabilities like XSS and clickjacking.

addElementChunk = function(){ 
    var html = '<div class="row dataPane"> Chunk of html elements </div>';
    var trustedHtml = $sce.trustAsHtml(html);
    var compiledHtml = $compile(trustedHtml)($scope);
    angular.element(document.getElementById('dataPanes')).append(compiledHtml);
}

Answer №2

By using the angular ng-repeat directive, you have the ability to dynamically append new div elements to your HTML.

Imagine you have an array with one element, and each time you click a button, a new element is added to the array and displayed in the "dataPane" div through repetition.

This is how your code could look:

HTML

<div ng-app="myApp" ng-controller="myCtr">
    <div class="col-md-12" id="dataPanes">
        <div class="row dataPane" ng-repeat="element in added_elements"> Chunk of html elements ( {{element}} ) </div>
    </div>

    <div class="col-md-12 text-right">
        <input type="button" class="btn btn-primary" value="Add dynamic row" ng-click="addMoreElements()" />
    </div>
</div>

JS

angular
.module('myApp', [])
.controller('myCtr', ['$scope', function($scope) {
    $scope.added_elements = ["elem 1"];
    $scope.addMoreElements = function(){
        $scope.added_elements.push("elem "+ ($scope.added_elements.length+1));
    } 
}])

This method allows you to easily add and bind data for your repeated rows in HTML without duplicating the entire HTML code.

See Demo in Action

Answer №3

If you want to add a new HTML element, you can easily do so using this method. It's simple to write and easy to understand. I hope this explanation will be helpful for you. The angular.element is used to access the HTML element. Here is an example of the HTML code:

 angular.module('myApp',[]).controller('myCtrl', function($scope){
 
 $scope.addElementChunk = function()
    {
       var htmlStr = '<div class="row dataPane"> Chunk of html elements </div>';
     debugger;
    angular.element(document.getElementById('dataPanes')).append(htmlStr);
    }
          
 });
 <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.3/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

 <div class="col-md-12" id="dataPanes">
   <div class="row dataPane"> Chunk of html elements </div>
 </div>

 <div class="col-md-12 text-right">
   <input type="button" class="btn btn-primary" value="Add dynamic row" ng-click="addElementChunk()" />
</div>
</div>

You can also view the demo on JSFiddle by following this link

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

Selecting elements using XPath

My goal is to target an i element using the following XPath: //div[contains(text(), "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="32565356564153565341725e5d5d1c515d5f">[email protected]</a>")]//parent//i[contains(@c ...

What is the best way to implement date range filtering in vue js?

Currently, I am delving into the realm of vue.js and experimenting with a filtering feature that involves date ranges. The process goes like this: initially filter by type, then proceed to filter by a specified date range, consisting of start and end dat ...

Is it possible to utilize getInitialProps in both _app.js and in individual pages within the application?

I am currently developing my first significant NextJS application. Instead of hardcoding the left navigation data directly into the app, I have set it up to pull in JSON data. This allows me to make minor changes to the site's navigation without havin ...

How to Handle Empty Input Data in JQuery Serialization

Having an issue with a form that triggers a modal window containing another form when a button is clicked. The second form includes an input field and send/cancel buttons. The goal is to serialize the data from the modal form and send it to a server using ...

Unable to find custom components when using react-router

My goal is to improve the organization of my Routes in React and separate concerns. I am currently utilizing react-router-dom version 5. Within my Application Routes component, I have structured it with 3 children components: AuthenticatedRoutes PublicRo ...

Losing authentication token when refreshing with Nuxt asyncData and Axios

While testing a get API that retrieves an array of mail data through Postman, everything seems to be working smoothly. However, when I implement the asyncData method to fetch the array in my code, it only works once. Upon page refresh, I encounter a 401 er ...

How to change the focus on a Material UI input field

I am facing an issue with resetting/clearing an input field using a button click: Take a look at the code here for reference. const searchInput = useRef(null); const clearInput = () => { searchInput.current.value = ''; searchInput ...

Persist user input even after reloading the page

In order to enhance the user experience, I would like to implement a feature where the data entered by the user is preserved even if they refresh, reload, or close the page. This includes retaining the selections made in the select elements. Additionally, ...

Obtain the src attribute of iframes using Robot Framework Selenium and store it as a variable

On a webpage, I have an iframe element that displays an html document representing a generated form. My goal is to create an automated Selenium script to validate specific values within this document. Currently, I am manually copying the URL from the ifram ...

Having difficulty linking a click event to an Anchor tag within a React component

Here is the code snippet for ComponentA.js: This is the return statement inside the component return ( ...... <a id="MytoolTip" ...... <ComponentB content={ ` <div class="share_cart_tt ...

Having trouble with the clear button for text input in Javascript when using Bootstrap and adding custom CSS. Any suggestions on how to fix

My code was working perfectly until I decided to add some CSS to it. You can view the code snippet by clicking on this link (I couldn't include it here due to issues with the code editor): View Gist code snippet here The code is based on Bootstrap. ...

What could be causing me to not receive the prepackaged error messages from Angular in my WebStorm 8?

Having some trouble here... my angular errors are always so cryptic, like this: I usually manage to figure out the issue on my own, but I'm really hoping someone can offer guidance on how to get those nice error messages that angular supposedly displ ...

What is the best way to place a parent div above its child element?

I'm currently dealing with a container div styled with background-color: red;. This container has around 12 children, and the last child is set with background-color: blue;. My goal was to position the container on top of the child with the blue backg ...

Tips for effectively organizing a collapsible list

Here is a list that I have: <ul> <li><span class="Collapsable">item 1</span> <ul> <li><span class="Collapsable">item 1.1</span></li> </ul> </ul> I am looking to create ...

Every time I use Get for ajax calls, I keep getting hit with a frustrating

Initially, I was making a call to a [web method] using the POST method. However, since I need to receive data back, I attempted to switch to using the GET method instead. The previous implementation using POST was successful. Unfortunately, using GET resu ...

Retrieve telephone number prefix from Cookies using React

Being able to retrieve the ISO code of a country is possible using this method: import Cookies from 'js-cookie'; const iso = Cookies.get('CK_ISO_CODE'); console.log(iso); // -> 'us' I am curious if there is a method to obt ...

Is AngularJS compatible with Mozilla Firefox version 3.0.11?

Can anyone confirm if the AngularJS is compatible with Mozilla Firefox version 3.0.11? I have built an application using AngularJS, but it's not functioning properly in this particular browser version. Could you please advise on the minimum version of ...

The implementation of a universal translation system in Express JS

I have developed a straightforward translation module for Express JS. It exists as a global object in the application scope and is initialized during application runtime: translator.configure({ translations: 'translations.json' }); I have i ...

What is the best way to create a seamless Asynchronous loop?

Adhering to the traditional REST standards, I have divided my resources into separate endpoints and calls. The primary focus here revolves around two main objects: List and Item (with a list containing items as well as additional associated data). For ins ...

Can text automatically adjust its size based on the browser's dimensions using CSS?

Can text automatically resize as the browser size decreases for liquid-based design using percentages? While images and divs can rescale, text scaling in percentages seems impossible! When set in percentages, it only changes the unified em setting for tha ...