What is the best way to add new input fields dynamically using the push() function in AngularJS?

I'm currently working on implementing an add more field feature in angularjs. Here is the code that I am using:
Javascript

 <script>
   function FruitsController($scope){
        var div = 'Apple';            
        $scope.fruits=[];
        $scope.addFruit=function(){
          $scope.fruits.push(div);
        }
    } 

 <script>

HTML

<ul><li ng-repeat="fruit in fruits">{{fruit}}</li></ul>
<button ng-click="addFruit()">Add</button>

The above code successfully appends the 'Apple' string in the body. However, my goal is to append an input type text field instead of a string. I have tried the following script, but it does not work as expected.

      <script>
       function FruitsController($scope){
            var div = '<input type="text">';            
            $scope.fruits=[];
            $scope.addFruit=function(){
              $scope.fruits.push(div);
            }
        } 

     <script>

I am aware that my current approach is incorrect. If you have any ideas or suggestions on how to add an input type in AngularJS, please share them with me.

Answer №1

If you want to display UI elements in HTML, here's an example of how your code could look:

    <ul>
        <li ng-repeat="item in items">
              <input ng-model="item">
      </li>
   </ul>
   <button ng-click="addItem()">Add</button>

And this is how a controller function might be implemented:

<script>
       function ItemsController($scope){
            var item = 'sample';            
            $scope.items=[];
            $scope.addItem=function(){
              $scope.items.push(item);
            }
        } 
<script>

Answer №2

To enhance your user interface experience, consider utilizing the ng-model attribute for input text boxes in order to enable seamless two-way data binding.

<ul>
    <li ng-repeat="item in items">
        <input type="text" ng-model="item">
    </li>
</ul>
<button ng-click="addItem()">Add</button>

Answer №3

<ul>
    <li ng-repeat="item in items">
        <input ng-model="item">
    </li>
</ul>
<button ng-click="addItem()">Add</button>

It is best practice to keep your UI/HTML code separate from your controller logic. Use Angular's two-way data binding with ng-model to update entries in the $scope.items array as input values change.

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

PhantomJs is only providing partial responses

I have been attempting to retrieve a response from the following URL using PhantomJS:- https://www.trivago.com/api/v1/bin/accommodation/2891353/deals?iPathId=34812&iRoomType=1&aRooms=&aDateRange%5Barr%5D=2017-05-24&aDateRange%5Bdep%5D=2017 ...

Updated Multer version causing issues with uploading image files

After using multer middleware to upload an image, I encountered an issue where the file image was showing up as undefined. This meant that I couldn't retrieve the name or file extension of the uploaded file. I'm not sure if this is an error with ...

Tips on increasing video size upon visiting a website. HTML, JavaScript, and potentially jQuery can be used for video animation

Is there a way to create a video pop-up in the same window when visiting a website? I want the video to increase in height from 0 to a specific height and move slightly upwards. Are there JavaScript or jQuery functions that can achieve this effect? I wou ...

Interactive navigation through scrolling with PHP onchange event

I need help with a PHP-related issue. I have a list of products that are generated dynamically using PHP. When a user clicks on one of the items in the list, the products are sorted. I also want the user to be smoothly scrolled to a new section of the page ...

What is the best way to access and manipulate data stored in a Firestore map using React?

In my Firestore database, I have a field with map-like data: coordinates:{_01:"copper",_02:"gold",_03:"iron"} When viewing this database in the Firestore admin panel, it appears like this: pic However, when attempting to list items using the following c ...

Focus on selecting just one button within Angular

By retrieving values from a database and displaying them using ng-repeat within a div: <div ng-controller = "myTest"> <div ng-repeat="name in names"> <h4>{{name.name}}</h4> <button ng-class="{'active ...

Activate event in jQuery when clicking on a blank area, away from any div element

I need help figuring out how to hide a div when empty space on the margins of the page is clicked, as opposed to just any area outside of the div. I've managed to achieve this functionality when certain other divs are clicked, but I'm stuck on im ...

Dynamic rule addition with JQuery Validation

I am searching for a method to dynamically incorporate the jQuery validation rules, as they are needed in various locations. For instance, a user can edit news in two different ways. The first method involves using a standard form with jQuery validation, ...

Bootstrap carousel button that tracks the number of clicks

Unfortunately, I am facing a challenging issue with creating a click counter for the Bootstrap carousel button. The problem seems to be related to the span element for the previous and next icons. The button counter is not registering clicks on the respec ...

Unexpectedly, the React custom component is failing to render as intended

I am anticipating the text "SMALL Medium, Big" to be displayed on the screen but unfortunately it's not showing up function Box(prop){ const ele = <div className={prop.cn}> </div> return ele } ...

Ensuring uniform sizing of anchor text using jQuery

My goal is to creatively adjust the font size of anchor text within a paragraph, making it appear as though the text is moving towards and away from the viewer without affecting the surrounding paragraph text. Currently, I am encountering an issue where th ...

Experimenting with JavaScript within an Immediately Invoked Function Expression

My team leader is requesting that I encapsulate my JavaScript code within an Immediately-Invoked Function Expression (IIFE). However, I am struggling to use spyOn in my Jasmine spec file. How can I properly use spyOn on the following: (function(){ fu ...

The toggle-input component I implemented in React is not providing the desired level of accessibility

Having an accessibility issue with a toggle input while using VoiceOver on a Mac. The problem is that when I turn the toggle off, VoiceOver says it's on, and vice versa. How can I fix this so that VoiceOver accurately states whether the toggle is on o ...

The alignment of elements in the div seems to be slightly skewed

Currently, I am in the process of creating a website with the temporary name yeet.io. I am facing an issue where I am attempting to center both an input and h1 element inside a div vertically and horizontally, but they keep appearing misaligned for some r ...

Tips for safely executing an SQL query with electron.js

I have a new project where I need to interact with an SQL database on the local network, but it's not located on the same system I'm working on (not SQLExpress). So far, I've figured out how to collect user input on a webpage and send that ...

Looking to dynamically load ng-model within an ng-repeat for a set of radio buttons

I am trying to dynamically load ng-model with data from an API call using ng-repeat for a series of radio buttons" This is my Controller: angular.module('app').controller('apiCallController', [$scope,'$http',function($scope, ...

Distinguishing between el and $el in Backbone.Js: What sets them apart?

I spent the entire afternoon struggling with this particular issue, but finally managed to resolve it. It ended up being a mix-up between assigning el and $el. Can anyone clarify the distinction between these two terms and provide guidance on when to use ...

What is the best way to save a scheduled cron reference in a database in order to deactivate it at a later time in a

I have implemented a system using cron to schedule push notifications. The user provides the push notification data and the scheduled time, and I use cron to send the notifications at the specified time. Below is the code snippet showing how I create a cr ...

When you click anywhere on the page, JavaScript's method __dopostback is triggered

I'm encountering an issue in my asp.net application where I have an html table. Specifically, when a user clicks on a td element within the table, I use JavaScript to store the id of that td element in a hidden field. Afterwards, I trigger __dopostbac ...

When altering the color of a mesh in Three.js, only a single face is impacted by the modification

I have a GLB model with multiple parts and hierarchy. My goal is to highlight a specific part of the assembly on mouseover. The code snippet I am using for this functionality is as follows: raycaster.setFromCamera( pointer, camera ); ...