Setting ng-model object with expression in AngularJs can be accomplished by using the Update/Assign

Currently, I am utilizing the MEAN stack in my application with AngularJS as the frontend. I have a question regarding how to use ng-bind to display the total sum of a value in another input in AngularJS. In my scenario, I have a table where I'm using a filter to calculate the total sum for the Sprice column, resulting in a total sum of 250. The desired outcome is to bind this total sum value to another input field using ng-model. For example, if the total sum for sprice is 250, then the expected answer for the bound value should also be 250. You can view the code on my Plunker here. I am unsure about where I might have made a mistake, so any assistance would be greatly appreciated.

  • In our table setup, we are utilizing a filter to calculate the total sum value for sprice. By using

    <td>{{resultValue | sumOfValue:'sprice'}}</td>
    , we were able to obtain the sum of 250.

  • The goal is to bind this total sum of sprice to another ng-module input named sprice_total, with the expected result being 250.

  • I have provided a reference Plunker here. If anyone knows a solution, please do help us out.

Snippet from My controller: Filter for sprice totalsum calculation:

    .filter('sumOfValue', function () {
return function (data, key) {
    debugger;
    if (angular.isUndefined(data) && angular.isUndefined(key))
        return 0;        
    var sum = 0;

    angular.forEach(data,function(v,k){
      if(v.confirm=='cancelled'){
        sum = sum + parseFloat(v[key]);
      }
    });        
    return sum.toFixed(2);
}

})

HTML snippet:

   <tr ng-repeat="ram in resultValue=(order.orderfood)  | filter: {confirm: '!cancelled'}">

                <td>{{$index + 1}}</td>
                <td>{{ram.sprice }}</td>


               </tr>
               <tr>
                 <td>sum</td>

                 <td>{{resultValue | sumOfValue:'sprice'}}</td>

               </tr>

I attempted to utilize ng-bind to transfer the sum to another input like so:

<input type="text" ng-model="sprice_total" ng-bind="sprice_total={{resultValue | sumOfValue:'sprice'}}">
  • Please ensure to update the Plunker to reflect any solutions provided. Thank you for your assistance.

Answer №1

My new directive, myModelValue, has been created specifically to assign your expression to the ng-model object.

If you would like more information, please follow this link.

var app = angular.module('plunker', []);

app.directive('myModelValue', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        scope: {
            model: '=ngModel'
        },
        link: function (scope, element, attr, controller) {
            attr.$observe('myModelValue', function (finalValue) {
                scope.model = finalValue;
            });
        }
    };
});
app.filter('sumOfValue', function () {
    return function (data, key) {
        debugger;
        if (angular.isUndefined(data) && angular.isUndefined(key))
            return 0;
        var sum = 0;

        angular.forEach(data, function (v, k) {
            if (v.confirm == 'cancelled') {
                sum = sum + parseFloat(v[key]);
            }
        });
        return sum.toFixed(2);
    }
}).controller('MainCtrl', function ($scope) {
    $scope.order =
  {
      "_id": "5836b64083d9ce0f0078eae8",
      "user": {
          "_id": "579bdf6123f37f0e00a40deb",
          "displayName": "Table 1"
      },
      "__v": 8,
      "total": "1824",
      "ordercar": [],
      "orderfood": [
      {
          "qty": "1",
          "confirm": "placed",
          "sprice": 250,
          "price": 250,
          "customise": "With Onion,Without Onion",
          "name": "Baasha Pizza"
      },
      {
          "qty": "1",
          "confirm": "cancelled",
          "sprice": 250,
          "price": 250,
          "customise": "With Onion,Without Onion",
          "name": "Baasha Pizza"
      }
      ],
      "phone": null,
      "order_source": "",
      "comment": "",
      "payment_mode": "",
      "nop": null,
      "rating": null,
      "bill": false,
      "complete": false,
      "laundry": false,
      "clean": false,
      "roomservice": false,
      "napkin": false,
      "waiter": false,
      "water": false,
      "name": "fgg",
      "created": "2016-11-24T09:43:28.413Z",
      "isCurrentUserOwner": true
  }
});
/* Your custom CSS code goes here */

body {
    font-size: 14px;
}

table
{
    border-collapse:collapse;
}
table, td, th
{
    border:1px solid black;
}
td{
    padding: 2px;
}
.servicetaxinclusive.true:before{
  color: green!important;
  content: "\f00c";
}
.servicetaxinclusivefalse:before{
  color: red!important;
  content: "\f00d";
}
.servicetaxexclusivetrue:before{
  color: green!important;
  content: "\f00c";
}
.servicetaxexclusivefalse:before{
  color: red!important;
  content: "\f00d";
}
<!DOCTYPE html>
<html ng-app="plunker">

<head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e889868f9d84899ac6829ba8d9c6dcc690">[email protected]</a>" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>    
</head>
...

I trust this meets your expectations.

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

Ways to decrease the height of the navigation bar in Bootstrap version 4.1

Struggling to figure out how to decrease the height of the navbar in bootstrap v4.1. I want it to be specifically 24px tall; Thanks, Richard. ...

Is the image clickable to slide back and forth?

How can I achieve a sliding effect when clicking on the bottom-coupon class? Currently, I am only able to implement show and hide functionalities without any sliding effects. The picture slowly hiding from right to left, with the coupon-layer sliding out f ...

Difficulty being faced in recognizing anchor tags through CSS selector methods by Mechanize

(Just wanted to check here since I didn't get much response on RailsForum lately.) Has anyone encountered issues with Mechanize not picking up anchor tags using CSS selectors? Here's a snippet of the HTML code: <td class='calendarCell& ...

Scroll Bar Menu (User-Controlled)

I'm looking for any libraries out there that can replicate or provide a similar horizontal scrolling menu to that of espn.com's homepage. I'm relatively new to jquery and feeling a bit lost on where to begin. I did some searching on Google, ...

Modifying the Nav-Bar background color causes the hamburger icon to become invisible

Here's the code I'm working with: <nav class="navbar navbar-expand-lg navbar-md-dark navbar-lg-light" style="background-color: #11100b;" id="nav-mob"> <div class="container"> <a ...

aiming for divs that have the css property "left=0"

While working with masonry.js, I find it challenging to add a class to the elements positioned on the far left of the viewport as they are not placed in a specific order by the plugin. Using the nth selector has been difficult to target them effectively. ...

Is it possible to retrieve values from my model when working with Django Templates and incorporating them in the JavaScript header?

With Django, I have managed to successfully retrieve and display data from my model in the content section of the template. However, I am facing issues retrieving data from the model in the header section of the template. Below is the code --> view.py ...

Loading tab content on click using jQuery

These tabs have a chrome-like appearance. When the first tab (Facebook) is clicked, it shows Facebook content. Clicking on the second tab (Twitter) displays the content of the first tab. Tabs three, four, and five show their respective contents without any ...

Display an image in a DIV by loading it from a URL provided in a TEXT BOX

I am having trouble loading an image into a div tag from a URL that is obtained from a text box. Here is my current code snippet, but I can't figure out what else needs to be done: <html lang="en"> <head> </head> <bod ...

Connect the scroll wheel and then proceed to scroll in the usual way

There are two div elements with a height and width of 100%. One has the CSS property top:0px, while the other has top 100%. I have implemented an animation that triggers when the mousewheel is used to scroll from one div to the other. The animation functi ...

Modify the input field for weight in WooCommerce to accommodate alphabetic characters

Is there a way to modify the WooCommerce Shipping weight field so that it can accept alphanumeric values, like: 500g / 1kg / 750ml / 2L I only need the weight for informational purposes and don't require any shipping. The location of the file re ...

Transmit a cookie from the front-end to the back-end using Angular in HTTP requests

I am currently in the process of developing a web application using AngularJS. This application consists of: a frontend component that solely retrieves data from a backend through multiple queries; a backend with various RESTful services, each returning ...

The strategic positioning of JavaScript/JQuery scripts in correlation with HTML

Here is an example of working code snippet: <a id="btnCapturePhoto" data-role="button" href="#page1">Capture Photo</a> <script type="text/javascript"> $($("#btnCapturePhoto").click(function captureImage() { alert('capture button ...

Display information exclusively upon clicking the Print button using AngularJS

I am currently working on a form that has multiple add-remove input field rows, essentially creating a report. I have included a print button in the form and would like to print only the data entered in the form in a structured manner, similar to a table w ...

The default theme has not been specified in Tailwind CSS

During my recent project, I utilized React, Next.js in combination with Tailwind CSS. In this project, I delved into styling customization by implementing react-slick for a specialized slider. To achieve the desired aesthetic, I made modifications to the r ...

How can I arrange the ng-class based on the clicked item's order?

http://plnkr.co/edit/pUtuZy?p=preview In this scenario, there are three different border classes available: .border1 { border: 1px solid #66FFFF; } .border2 { border: 1px solid #33CCFF; } .border3 { border: 1px solid #0099FF; } The goal is to as ...

Decrease the width of a div element when its sibling element expands

I am working on a layout where I have two divs placed side by side within a parent div. The left div will have text content, while the right div will contain an image. I want to implement functionality where on button click, the right div can expand or red ...

JHipster: The CSS styles applied on the production environment at runtime may vary from those applied on the

I have integrated bootbox to display a dialogue box: bootbox.confirm({ message: "Do you confirm the submission of the CRA request?", backdrop: false, className: "on-top-bootbox-alert-2", buttons: { confirm: { label: 'Yes', ...

Bursting at the seams: concealed issues

I am currently facing an issue with a facebook like button placed in the caption section of a slideshow div, located at the far bottom right corner. The problem arises when the 'post to wall' prompt pops up below the like button, but is cut off d ...

javascript - determine whether a hyperlink has been accessed

Is there a method to determine if a link has been visited? In Firefox, the color of a link changes after clicking on it, which leads me to believe it is possible. Edit: This question pertains to a Firefox extension, so I am unable to modify the HTML or CS ...