Make ng-repeat trigger function again in data binding

I am currently utilizing the ng-repeat directive within a table to display a list of items along with their respective prices.

  • The price is dynamically linked to itemPrice(item), which has been defined in my controller.
  • This function calculates the price based on the value of $scope.orderType.
  • orderType is connected to a dropdown menu (select) in the HTML markup.

Is there an optimal method to ensure that all prices are updated whenever the order type is changed?

HTML

<select ng-model="orderType" ng-options="name for name in orderTypes"></select>

<!-- ... -->

<tr ng-repeat="item in items">
    <td>{{ item.name }}</td>
    <td><input type="checkbox" ng-model="item.is_used"></td>
    <td><input type="number" ng-model="item.quantity" min="0" max="100"></td>
    <td>{{ itemPrice(item) | currency:"$" }}</td>
    <td>{{ itemPrice(item) * item.quantity | currency:"$" }}</td>
</tr>

JavaScript

.controller('OrderCtrl', ['$scope', '$http', function($scope, $http) {
    
    // Define different order types
    $scope.orderTypes = ['Buy Back', 'Sale'];
    $scope.orderType = $scope.orderTypes[1];

    // ...
    
    // Retrieve the price of an item
    $scope.itemPrice = function(item) {
        if ($scope.orderType === 0) {
            return item.price_buy_back;
        } else if (item.is_used) {
            return item.price_used;
        } else {
            return item.price_new;
        }
    }
    
    // ...
    
}]);

Answer №1

Due to my busy work schedule, I'm unable to create a plunker for validation:

My recommendation is to avoid using a function ("itemPrice"). Instead, calculate this value beforehand and store it in a variable within your item structure.

When the type changes (use ng-change or $scope.$watch..), recalculate and update the variables within your item structure.

Here's an example:

.controller('OrderCtrl', ['$scope', '$http', function($scope, $http) {

    // Set up order types
    $scope.orderTypes = ['Buy Back', 'Sale'];
    $scope.orderType = $scope.orderTypes[1];

    var itemPrice = function(item) {
        if ($scope.orderType === 0) {
            return item.price_buy_back;
        } else if (item.is_used) {
            return item.price_used;
        } else {
            return item.price_new;
        }
    }

    var setItemPrices = function(){

        for(var i = 0; i < $scope.items.length; i++)
        {
            $scope.items[i].itemPrice = itemPrice($scope.items[i]);
        }
    }

    $scope.$watch("orderType", function(newVal, oldVal){
           //update itemPrices
           .... setItemPrices();
    });
    // ...

}]);

Answer №2

It's funny how we sometimes overlook the simplest things. I initially blamed my lack of Angular experience for the issue, only to realize it was actually a JavaScript error.

The root cause was the improper comparison in the itemPrice function where $scope.orderType was being compared to an integer instead of a string. This mistake stemmed from setting $scope.orderType as a string earlier in the code (

$scope.orderType = $scope.orderTypes[0]
).

With the correction made, the ng-repeat now functions correctly, triggering the itemPrice method whenever there is a change in the value of $scope.orderType.

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

Passing Node.js MySQL query results to the next function within an async.waterfall workflow

In my node.js code using express, I have set up a route to request data from a mysql database. My goal is to pass the returned JSON in tabular form to another function to restructure it into a hierarchy type JSON. I have individually tested the script to ...

Click to open the file browser by using the onclick event in Material-table actions

Currently, I am working with a Material table component from "@material-table/core" My goal is to implement an action that enables users to upload a file within this table. I am facing some challenges on how to trigger the file browser when the ...

What is the process for establishing a connection between a websocket and an external API?

Currently, I have a route configured to fetch the weather data for a specific city using the openweathermap API Here is the code snippet from my index.js file: var express = require("express"), router = express.Router(); var weather = require("ope ...

Instructions on implementing getJSON in this code

I recently set up a chained select box with JSON data to populate options, using this Fiddle. While the data is hardcoded for now, I am looking to load it using the $.getJSON() method. However, despite my efforts, I haven't been able to get the code r ...

Is there a way for me to make a local HTML page save text directly to a file on my computer?

Currently, I am working on a straightforward HTML+JavaScript application that is designed to be loaded from a local file and run within the user's browser. The main functionality of this app will be to enable users to input text into a textarea and sa ...

Struggling to get your HTML to Express app Ajax post request up and running?

I’m currently in the process of creating a Node Express application designed for storing recipes. Through a ‘new recipe’ HTML form, users have the ability to input as many ingredients as necessary. These ingredients are then dynamically displayed usi ...

Does the notion of "Execution context and the stack" only pertain to web browsers?

Does the concept of "Execution context and the stack" only apply to browsers, or is it also utilized in other environments such as NodeJS? I've crafted 2 statements but unsure if they are accurate: 1- "The environment for JavaScript is not solely the ...

"Upon exiting the Chrome tab on an iPhone, the Opentok stream's hasAudio property returns false

While switching to a different tab in Chrome on iPhone (without closing it), the publisher's stream.hasAudio value changes to false. It switches back to true only upon returning to the stream tab. Can anyone explain why this occurs and how to stop has ...

Understanding the functionality of app.locals within app.get in an Express application and how to effectively parse data

I am currently developing a parse application using express. In my index file, I want to display different information to users based on whether they are logged in or not. However, I am facing an issue with storing the flag and logged-in user name using ap ...

Can the autoscroll offset be adjusted while dragging?

I am developing a single-page application using Vue.js. The user interface consists of three main components: A fixed navbar at the top with a z-index of 2 A fixed sidebar on the left with a z-index of 1, and padding to accommodate the navbar A central ar ...

Invoke Javascript through CSS selector

On my webpage, I have implemented a mousemove-mask feature that was inspired by an existing codepen. However, there is one significant issue that I can't seem to resolve on my own. Despite my attempts to fix it, I believe someone with more expertise c ...

Is there a way to retrieve files from a main directory as well as all its subdirectories?

I'm looking to find a way to retrieve all JavaScript files located in the main directory and any subdirectories for my discord.js command handler. How can I make this happen? I have a functioning code snippet that successfully retrieves all .js files ...

Can someone show me the JavaScript code to split a string at every instance of ' '?

Hey there! I have a question about manipulating strings. Take a look at this example: var string = '"In Another World" "Magic Books"' I want to create an array that contains every name within the [""]. How can I ach ...

Using jQuery, learn how to successfully call a selector from dynamic content

I am currently facing a challenge with a table that is generated server-side and then appended to the view page (client-side). Since the table is not directly included in the DOM, I am using the StickyTableHeaders jQuery plugin to create a sticky header fo ...

Utilizing AJAX to dynamically update a div's content by extracting a specific div from the retrieved data

Although I believe my code is correct, I am not very familiar with AJAX and have been struggling for hours to get it right. I've tried various approaches, including using filters, but nothing seems to work. The issue I'm facing is that the chat m ...

Button for copying URL and pasting it to clipboard available for use on desktop, iOS, and Android platforms using JavaScript

Is it feasible to use JavaScript/jQuery to copy the current URL and paste it into the clipboard using pure JS? Specifically, I am targeting phone users, like those with iPhones running Safari. I want to create a button that can automatically retrieve the ...

The ul cannot be hidden if there are no li elements within it

Currently, I am attempting to hide the unordered list (ul) on a specific page using AJAX due to certain sections of the site being Ajax-based. <ul class="sub-nav-20-m" id="filtersList_m"> </ul> Below is the code that I hav ...

Implement jQuery to toggle a class on click for added functionality

I am attempting to create a box that changes color when clicked. When the box is first clicked, it will turn red by adding the class red, and if clicked again, it will change to blue. The colors alternate with each click, but I am unsure of how to achieve ...

Is there a bug in Safari 8.0 related to jQuery and backslashes?

I am using Mac OS 10.10 Yosemite and Safari 8.0. Attempting to read an XML (RSS) file: <content:encoded>bla bla bla</content:encoded> The Javascript Ajax method I am using is: description:$(valeur).find('content\\:encoded&apo ...

I initially had ngRoute set up in my app, but decided to make the switch to ui-router. However, now it seems like

I currently have an application set up using express and angular. I decided to transition to ui-router in order to utilize multiple views, but it doesn't appear to be functioning as expected. app.js app.use(express.static(path.join(__dirname, ' ...