A step-by-step guide to dynamically adding HTML content on a button click using AngularJS

Can HTML content be added on Button Click event using AngularJS?

Here is the code from my index.html:

<div class="form-group">
    <label for="category"> How Many Questions Do You Want to Add? </label>
        <div class="col-sm-10">
            <input type="text" class="form-control input-mini" id="questionNos" name="questionNos" placeholder="Nos." ng-model="myData.questionNos">
                <div class="input-append">
                    <button class="btn-warning btn-mini" type="button" ng-click="myData.doClick()">Generate</button>
                </div>
        </div>
</div>

I want to dynamically add HTML divs based on the quantity entered.

And here is my myApp.js file:

angular.module("myApp", []).controller("AddQuestionsController",
            function($scope) {
                $scope.myData = {};
                $scope.myData.questionNos = "";
                $scope.myData.doClick = function() {
                    //Do Something...????
                };
            });

Answer №1

It is definitely achievable. I recommend binding your Div elements to the viewModel properties and creating the viewModels in your doClick function.

I suggest avoiding direct manipulation of Html within your viewModel.

Consider the following example:

<div class="form-group">
    <label for="category"> How Many Questions Would You Like to Add? </label>
        <div class="col-sm-10">
            <input type="text" class="form-control input-mini" id="questionNos" name="questionNos" placeholder="Nos." ng-model="myData.questionNos">
                <div class="input-append">
                    <button class="btn-warning btn-mini" type="button" ng-click="myData.doClick()">Generate</button>
                </div>
                <div ng-repeat="q in myData.questions">
                      <!-- BIND TO Q HERE -->
                </div>

        </div>
</div>

Within the doClick function:

 $scope.myData.doClick = function() {
                    var newQuestions = getNewQuestionViewModels($scope.myData.questionNos);
                    for (var i = 0; i < newQuestions.length; i++) {
                        $scope.myData.questions.push(newQuestions[i]);
                    }
                };

Answer №2

One must organize questions in a collection and repeat the process.

DEMO

HTML:

<div>
    <input type="text" ng-model="data.qcount">
    <button type="button" ng-click="data.add()">Add</button>
</div>
<div>
    <div ng-repeat="q in data.questions track by $index">
        <pre>{{ q | json }}</pre>
    </div>
</div>

JS:

$scope.data = {
    questions: [],
    qcount: 0,
    add: function() {
        var dummy = {
                'title': 'Q title',
                'body': 'Q body'
            },
            newQ = [];

        for (var i = 0; i < $scope.data.qcount; ++i) {
            newQ.push(dummy);
        }

        $scope.data.questions = $scope.data.questions.concat(newQ);
        $scope.data.qcount = 0;
    }
};

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

Designing a web application with Angular2

As a newcomer to Angular2, I have recently started working on creating a simple hello world application. I have come across the concept of Modules and Components in Angular2. My main source of confusion lies in how to properly design an Angular2 applicat ...

Modifying the class of multiple images within an array

I am excited to share my first post here and express my gratitude for all the solutions I have found on this platform. I encountered an issue with using .removeClass and .addClass in my recent program. I am loading multiple pictures into an array called F ...

Utilizing interactive parameters in ui-router

Currently, I am in the process of creating a search application using angular along with ui-router. Specific Requirements: The search form consists of numerous fields, all of which must be optional. It is necessary for users to be able to share the URL ...

Struggling to integrate an audio player specifically for mp3 files and feeling quite perplexed by the process

I'm struggling with implementing an audio player for a file sharing platform, specifically only for .mp3 files. I have successfully implemented a function for images (.jpeg and others), but I am unsure how to do the same for mp3 files. function is_au ...

Creating a blurred background effect when a React portal is presented

I have implemented React portals to display a modal popup after the form is submitted. However, I am facing an issue with blurring only the background while showing the modal, similar to what is shown in picture 2. Initially, I tried using document.body.st ...

Animation not properly synced with Bootstrap 4 Dropdown hide event

Could you please check out my codepen for clarification: http://codepen.io/anon/pen/oLZOyp Essentially, I have integrated two animations using animate.css into Bootstrap 4 show.bs.dropdown and hide.bs.dropdown events. The animations work on the first show. ...

Using AJAX to Interact with PHP

Currently, I am facing a problem with my PHP code where my For each loop is not properly waiting for the response of the AJAX call. I have attempted to incorporate Promise functions to solve this issue but unfortunately, it did not work out as expected. ...

Is the jQuery ajax .done() function being triggered prematurely?

Struggling with a problem here. I'm dealing with this code (simplified): var initializeZasilkovna = function () { // Initialize object window.packetery.initialize(); }; // Check if the object doesn't exist if (!window.packetery) { // It ...

IE is failing to trigger jAlert function

When I validate a text box by pressing the enter key on my keyboard, the validation works fine but the JAlert doesn't show up. However, when I call the same function on a button click, the alert shows in IE. I am quite confused by this behavior and wo ...

What is the best way to include rxjs in an npm library - as a dependency, peer dependency, or both?

After researching numerous posts and articles on dependencies versus peerDependencies, I am still not entirely certain what to do in my particular situation.... I have a library (which is published to a private npm repository) that utilizes rxjs; for exam ...

Guide to capturing and playing audio on iOS6 with HTML5

Our team is currently working on a web application using HTML5 and Javascript. We are facing a challenge with implementing voice recording functionality, as the Wami Api we tried is not compatible with iPad due to its use of flash for recording. Could yo ...

The event "click .className" within the Marionette module is failing to trigger

I'm facing an issue with some code that I've written. Here's a snippet of what it looks like: myApp.module(args, function(args){ Views.MainView = Marionette.ItemView.extend({ //template, tagName, className down: false, events: ...

Ways to schedule the execution of a script at a specific time using Node.js

Every time the readDirectory function is called, it checks if any file created date is more than 30 days ago and removes that file from the directory. While this functionality is working correctly, I am concerned about its efficiency. To address this issue ...

Manipulating the value of an array obtained from an API alters its data when trying to log it in the render function of a React TSX component

My program can fetch data from an API I created using a component that interacts with the backend: import React, { Fragment, useEffect, useState } from 'react' import { Button, Stack } from '@mui/material'; import TabsComponent from &ap ...

Automatically log out users in AngularJS after a specified period with session timeouts

I recently developed a website using AngularJS and now I'm faced with the task of implementing an automatic logout feature if the user has been inactive for more than 10 minutes after logging in. Additionally, I need to ensure that the local storage r ...

What is the solution to preventing Angular 1.3 ngMessages from affecting the size of my form?

Hey there, I'm diving into front-end design for the first time. My issue is with a form that I want to use ng-messages for validation error messages. Currently, my form's size changes depending on whether there are errors displayed or not, and it ...

Utilizing Typescript Generics in Arrow Function to Combine Two Arguments

For instance, I am working with this code in a .tsx file extension const Add = <T,>(arg0: T, arg1: T): T => arg0 + arg1; const A = Add(1, 2); const B = Add('1', '2') However, I am encountering an issue, as there is an error m ...

Can you explain the purpose of the array as the second parameter in an Angular directive?

I need to understand a specific customer directive so I can implement it into our AngularJS application. The second parameter seems to be a part of a string and then the main function: mainApp.directive('uiCalendar', ['uiCalendarConfig&apo ...

Visual Studio is not compatible with AngularJS routing functionality

I am working on my AngularJS project using VS 2015. I've encountered an issue with routing that I can't seem to resolve. Whenever I click on the "Add" hyperlink, the URL in the browser's address bar shows as follows: "http://localhost:21530/ ...

Nested promise not being waited for

As someone new to all things asynchronous, I am currently facing a challenge. I want to ensure that a file exists before updating it, creating the file if necessary. However, I am struggling to figure out how to achieve this. I am aware of the option to u ...