Is there a way to add another item to a repeated DOM element without having to modify the ng-repeat scope?

I am working with a list of items using ng-repeat

<div layout="column"  
      class="md-whiteframe-1dp"   
      ng-repeat="item in child.items track by item._id"  
      id={{item._id}}child>
</div>

I am looking to add an additional DOM element (another itemToAppend) to the list without affecting the child.items scope. I simply want to append a similar-looking DOM element but with new data.

itemToAppend = {name: "itemToAppend", _id: "111"}

Can anyone advise me on how to achieve this? Thank you in advance!

Answer №1

To achieve this, create a new scope variable with an empty array type and push the value on button click. In the example below, I have used a text input and a button for demonstration purposes. Feel free to customize it according to your needs. Here is the code snippet:

HTML:

<head>
  <link rel="stylesheet" href="style.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>
  <script src="script.js"></script>
</head>

<body>
  <div ng-app="sampleApp">
    <div ng-controller="myController">
      <input ng-model="newItem" type="text" />
      <button ng-click="add(newItem)">Add</button>
      <div ng-repeat="arr in child">
         {{arr}}
      </div>
      <div ng-repeat="arr in tempchild track by $index">
       {{arr}}
     </div>
    </div>
 </div>
 </body>
</html>

JS:

(function(angular){
  var module = angular.module("sampleApp",[])
   .controller("myController", ["$scope", function($scope){
    $scope.child = ['A', 'B' , 'C', 'D'];
    $scope.tempchild = [];
    $scope.add = function(item) {
      $scope.tempchild.push(item);
   };
 }]);
})(window.angular);

In the code above, be sure to include another ng-repeat that iterates through the new $scope variable.

For a complete example, check out this link

Answer №2

Including a new feature, I implemented a button to assist users in adding items.

<input ng-model="newItem" type="text"></input>
        <button ng-click="add(newItem)">Add</button>
$scope.itemsInFolder = ["A", "B", "C", "D"];
   var additionalItems= $scope.itemsInFolder;
    $scope.add = function(item) {
        additionalItems.push(item);
    };

Connect additionalItems with ng-repeat

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

Generating a fresh array based on the size of its existing elements is the key feature of the ForEach method

When running this forEach loop in the console, it extracts the property "monto_gasto" from an array of objects in the firebase database. Here's how it looks: something.subscribe(res => { this.ingresos = res; ...

Triggering server-side code (node.js) by clicking a button in an HTML page created with Jade

I am currently working on developing a web application and have encountered an issue where I need to execute some server-side code when a button is clicked (using the onClick event handler rather than the Submit button). My tech stack includes Node.js, Exp ...

The jQuery UI accordion fails to function properly after refreshing the data

I am facing an issue with my HTML page where data is loaded dynamically into accordions. The accordion functionality is implemented inside a function, which is called at regular intervals to refresh the data. Initially, the accordion displays correctly, bu ...

Program does not display the expected alert message when using if/else statement

I'm grappling with creating a basic program that accomplishes the following: Develop a function declaration named changePowerTotal which accepts: The total current power generated (a numeric value) A generator ID (a number) The new status of ...

Top Strategies for PHP - Managing Directs and Header Content

PHP is a versatile language frequently used for generating 'templates' like headers to maintain a consistent look across websites and simplify updates via require or include commands. Another common task involves managing log-ins and redirecting ...

Tips on how to increase and update the index value by 2 within an ngFor loop while maintaining a fixed format

I have a specific template layout that displays only two items in each row as shown below. I want to use the ngFor directive to iterate through them: <div class="row" *ngFor="let item of cityCodes; let i = index"> <div class="col-6" (click)= ...

Issue with document.referrer in Firefox: Unexpected behavior

I attempted to utilize the document.referrer function. It functions correctly in Google Chrome, however it does not yield the expected results in Mozilla Firefox. if (document.referrer.indexOf('stringToCheck') > 0) { //insert code here ...

Issue: unhandled exception: Marketplace URI is not valid

It seems like I am the first one in this community to ask a question related to balancedpayments. I recently started working with balancedpayments. Here's what I've done so far: Set up a test marketplace Added a "webhoo ...

What is the best way to merge two JSON objects linked by a foreign key in Angular?

Looking to display data from two JSON objects in a table, connected by a foreign key. The first set of JSON data is as follows: $scope.items = [ {status_id: 1, type: 1}, {status_id: 2, type: 2}, {status_id: 1, type: 3}, {status_id: 1, typ ...

display PHP JSON information using jQuery AJAX

I'm completely new to this subject. I have a Json result that looks like the following : { "span": " 1", "numcard": "12", "chan": " Yes", "idle": "Yes", "level": "idle ", "call": "No ", "name": "" } My goal is to ...

Error encountered while compiling ./node_modules/@material-ui/core/ButtonBase/ButtonBase.js

I've encountered a frustrating error message: Failed to compile ./node_modules/@material-ui/core/ButtonBase/ButtonBase.js Module not found: Can't resolve '@babel/runtime/helpers/builtin/assertThisInitialized' in 'E:\IT&bsol ...

How to link AngularJS controller from a different module in routing

My current project involves creating a complex app with a structured design: Each module is organized in its own folder structure, including controllers, directives, and more. Within each folder, there is an index.js file along with other files for separ ...

Why isn't my onClick event functioning as expected?

I used the handleClick function in an onClick event, but it's showing an error (this is not defined). var Buttons = React.createClass({ getInitialState() { return { field: ':P ' } }, handleClick(field ...

Reserved space for both double and single quotation marks

I've created a function that generates a table of specified size with predetermined content in each cell, and displays it within a designated div ID. generate_table(4, 4, 'Cell Content', 'display') To test this function, I added a ...

Why does the parent URL become the origin for an AJAX request coming from an iframe?

I am facing an issue with a website where I need to load an iframe from a different subdomain. The main website is hosted on portal.domain.com, and the iframe is on iframe.domain.com. To make requests to iframe.domain.com from portal.domain.com, I decided ...

Utilize Puppeteer for Web Scraping to Extract Products with an Array of Images

I am currently developing my portfolio by working on a variety of small projects, with my current focus on web scraping. Using Puppeteer, I have successfully scraped basic test websites. However, my goal now is to tackle more advanced challenges, such as ...

Switch from manipulating the DOM to using Angular binding to update the td element with fresh information

When I click the edit button on a tr Element, the tdElement for the redirectUrl should become editable. By using the id of the tdElement and changing the contenteditable attribute to true, I can then use JQuery to retrieve the newly typed data. <tr ng- ...

JavaScript Ping Pong Challenge

I'm currently investigating why the browser returns NaN for the Positions. The game is being rendered in a loop and updated as soon as the monitor is ready, which is defined in the update() function and runs infinitely. The reset() function is a part ...

Is there a way to create a nested object literal that will return the length of

I am working with JSON data that includes different locations (sucursales) and cars for each location. How can I write a function to calculate the total number of cars across all locations? [{"sucursal": "Quilmes", "direccion&q ...

When attempting to use JQuery autocomplete, the loading process continues indefinitely without successfully triggering the intended function

Currently, I am utilizing JQuery autocomplete to invoke a PHP function via AJAX. Below is the code snippet I am working with: $("#client").autocomplete("get_course_list.php", { width: 260, matchContains: true, selectFirst: false }); Upon execution, ...