Model updating with the addition of an item and triggering a secondary ng-repeat for refreshing

As I was working on the phone tutorial, I found myself pondering how to implement a specific use case.

  1. The browser renders a list of phones.
  2. When the user clicks on add phone for one of these phones,
  3. the function addItem is triggered and adds that phone into the array phonesInCart.
  4. Then, the list with the phones in the cart ($scope.phonesInCart = [];) is updated.

You can check out the logic demonstrated in my codepen demo.

<body ng-controller="PhoneListCtrl">
<h3>Phones we sell</h3>
<ul class="phones">
  <li ng-repeat="phone in phones | filter:query | orderBy:orderProp">
    <b>{{phone.name}} </b>
    <button ng-click="addItem(phone)"
            ng-disabled="{{phone.orderReadonly}}">add phone</button>
  </li>
</ul>

<h3>Phones in your cart</h3>
<ul>
  <li ng-repeat="phoneInCart in phonesInCart"> 
    {{phoneInCart.name}}
  </li> 
</ul>
</body>

Additionally, here's the relevant JavaScript code:

$scope.phonesInCart = [];
$scope.addItem = function(phone) { 
    // These lines do not affect the UI
    phonesInCart.push(phone);
    $scope.$apply();
}

Current Status

The list is rendered and the 'addItem' function is activated. However, at present, the list of phones in the cart is not being updated or displayed.

My Query

I am curious about:

  • What needs to be done to populate a second array phonesInCart[], refresh another ng-repeat?
  • Do I need to create/use more than one controller like
    phonecatApp.controller('PhoneListCtrl'
    in order to enable a secondary ng-repeat?

Answer №1

If you want to make your code work properly, try using $scope.phonesInCart.push(phone) instead of phonesInCart.push(phone).

$scope.phonesInCart.push(phone)

Make sure to update the variable name in order to loop over it correctly in your html.

UPDATE: When calling addItem with an ng-click directive, there is no need for $scope.$apply. It's possible that you are encountering an error message like 'digest loop already in progress' due to this unnecessary addition in your current code.

Answer №2

I made some adjustments to your codepen code.

  • One thing to note is that you forgot to include $scope when pushing items into the array of phones.
  • In order to allow multiple instances of the same phone to be added to the list, you should include track by $index in your ng-repeat directive.
  • The $scope.apply inside your addPhone function is unnecessary - the digest cycle will be triggered automatically when updating the scope variable array.
  • Additionally, there is no need to use $watch on the phonesInCart array for the same reason as mentioned above.

Here's an updated pen with all these modifications applied. If you have any further questions, feel free to ask :)

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

Why should one bother with using the then() function in AngularJS?

Consider this scenario with the following code: self.findSongsInAlbum = function(album) { return self.query( "SELECT * FROM MusicLibrary WHERE Album LIKE '%" ...

How to reference 'this' within a d3 callback when using Angular 7

In an Angular directive, I am trying to access a class-level variable inside a callback function. To achieve this, I used an arrow function but the 'this' keyword is still not pointing to the directive. this.itemRects.selectAll('rect') ...

What is the importance of using a polyfill in Babel instead of automatically transpiling certain methods?

Recently, I have been diving into a course that delves into the use of babel in JavaScript. It was explained to me that babel, with the preset "env," is able to transpile newer versions of ES into ES5. However, I found myself facing a situation where the a ...

What is the best way to retrieve all dates that are older than 30 days using JavaScript?

I have the following code snippet as a reference and I'm attempting to retrieve a list of dates from 30 days before. What do I need to change? Date.prototype.addDays = function(days) { var newDate = new Date(this.valueOf()) newDate.s ...

Guide on choosing a specific div element from a different page using AJAX

I have a Social Media platform with posts, and I am trying to display the newest ones using JavaScript (JS) and AJAX. I attempted to reload my page using AJAX and insert it into a div element, but now the entire website is loading within that div element, ...

Is there a way to identify and count duplicate data-items within an array, and then showcase this information using a react view?

If we have an array like this: [{id: 1, name: "chocolate bar"}, {id:2, name: "Gummy worms"}, {id:3, name:"chocolate bar"}] Is there a way to show on the dom that we have "2 chocolate bars and 1 Gummy Worms"? ...

Navigating files using NodeJS and ExpressJS

Can NodeJS (or ExpressJS) facilitate the following task? Although I appreciate the flexibility that routing provides, I find the configuration process quite cumbersome. (I don't consider myself an expert in Express) For instance, imagine an applicat ...

Merging the functions 'plainToClass' and 'validate' into a single generic function in NodeJs

Here's the issue I'm facing: export const RegisterUser = async (request: Request): Promise<[number, UserResponse | { message: any }]> => { let userRequest = plainToClass(UserRequest, request.body); let errors = await validate(u ...

Ways to showcase an alert or popup when clicking?

I am utilizing a date picker component from this site and have enabled the 'disablePast' prop to gray out past dates preventing selection. Is there a way to trigger an alert or popup when attempting to click on disabled days (past dates)? Any sug ...

Display the source code of an HTML element when clicked

Is there a way to show the source code of an element on a webpage in a text box when that specific element is clicked? I am wondering if it is feasible to retrieve the source code of an element upon clicking (utilizing the onClick property), and subseque ...

What is the best method for removing extra spaces from an input field with type "text"?

I have an input field of type "text" and a button that displays the user's input. However, if there are extra spaces in the input, they will also be displayed. How can I remove these extra spaces from the input value? var nameInput = $('#name ...

Malfunctioning string error in Django view caused by boolean inconsistencies

Looking to extract variables from a post request made by Javascript. Upon inspecting the received variables in my view, I found the following: >>> print request.body {"p":"testprd","cash":false,"cheque":true,"debit":false,"credit":true} The valu ...

Setting up computed properties in VueJSSetting up computed values in

I am currently working on developing a lottery number service, and I am curious about how to set up computed properties. I came across the Vue.js documentation for computed properties at https://v2.vuejs.org/v2/guide/computed.html#Computed-Properties. I tr ...

Setting up bower and static files in a dotnet core project

After creating a new dotnet core project using the command dotnet new webapi, I now have the following folders and files in my project: bin controllers obj wwwroot (currently empty) dotnet.csproj Program.cs Startup.cs Now, I am lookin ...

An error occurred while trying to add a property to an array because the object is not extensible: TypeError -

In my code, there is an object named curNode with the following structure: { "name": "CAMPAIGN", "attributes": {}, "children": [] } I am attempting to add a new node to the object like this: curNode!.children!.push({ name: newNodeName, ...

Deleting a record in MongoDB based on a specific value present in a column

I am in search of more information about delete triggers in MongoDB. Source: Query on MongoDB Delete Triggers I am interested in converting DELETE operations to UPDATE + AUTOMATIC DELETE. To achieve this, I plan to introduce a new field called "flag" ...

Is it possible to utilize EmberJS or other frameworks without the necessity of setting up its server?

I am in search of a JavaScript framework that offers the following features: MV* Well-structured HTML file as template Fast rendering (possibly using virtual DOM) Ability to combine and be compatible with other plugins or libraries Edit on tablet IDE app ...

Having issues updating table with Javascript after form submit in IE and Edge browsers

My current setup involves using Contact Form 7 in Wordpress to store data in a MySQL Database with Submit-Form. Now, I am working on reloading a table containing this data after the form submission. Here is the script I am currently using: /* FORM RELOAD ...

I'm looking for some help with creating a visualization using JavaScript or Python. Can anyone offer some guidance?

// Defining the dimensions and margins of the graph var width = 460 var height = 460 // Appending the svg object to the body of the page var svg = d3.select("#my_dataviz") .append("svg") .attr("width", width) .attr("height", height) // Reading ...

Seamlessly adaptive HTML5 video playback

Has anyone figured out how to make an HTML5 video in an absolutely positioned <video> element resize to fit the window width and height without ever getting cropped? Many solutions I've come across rely on using the <iframe> tag, which is ...