Как найти сумму нескольких строк с помощью angularjs - PullRequest
1 голос
/ 08 июля 2019

Я пытаюсь найти итог, но он показывает 0. Я пытаюсь на локальном сервере xamp.

<div data-ng-app="myapp" data-ng-controller="CartForm">
  <table>
    <tr ng-repeat="x in names">
      <td>{{ x.price }}</td>
      <td><input type="number" ng:model="x.qty" /></td>
      <td>{{ x.qty * x.price | currency: "Rs " }}</td>
    </tr>
    <tr>
      <td>Total:</td>
      <td>{{ total() }}</td>
    </tr>
  </table>
</div>

Ответы [ 2 ]

0 голосов
/ 08 июля 2019

Попробуйте что-нибудь подобное.

$scope.getTotal = function(){
    var total = 0;
    for(var i = 0; i < $scope.cart.products.length; i++){
        var product = $scope.cart.products[i];
        total += (product.price * product.quantity);
    }
    return total;
}
0 голосов
/ 08 июля 2019

Соглашения о синтаксисе для ng-модели не подходят, но они будут работать.

Использование ng-model = "x.qty"

Но, чтобы получить общий итог, необходимо записать функцию total () в файл JS.

Обновление 1:

Файл HTML:

<body>  
    <div data-ng-app = "myapp" data-ng-controller = "CartForm">
        <table>
            <tr ng-repeat = "x in names">
                <td>{{ x.price }}</td>
                <td><input type = "number" ng-model = "x.qty" /></td>
                <td>{{ x.qty * x.price | currency: "Rs " }}</td>
            </tr>
            <tr>
                <td>Total:</td>
                <td>{{ total() }}</td>
            </tr>
        </table>
    </div>
</body>

Файл угловой JS:

var myApp = angular.module('myApp', []);
myApp.controller("CartForm", function ($scope) {
    $scope.names = [
        {price:2000, qty:3},
        {price:7000, qty:6},
        {price:3000, qty:5}
        ];

    // Function for performing total of all.
    $scope.total = function() {
        var total = 0;
        for(var i = 0; i < $scope.names.length; i++){
            var name = $scope.names[i];
            total = total + (name.price * name.qty);
    }
    return total;
    };
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...