0

I have written this code online dynamic form jsFiddle code

The total and grand total are not auto updating. I had a more simple example before and it was working with a single model item, but then I made an array and now it won't work. My real program I am building is going to have many more fields and I am trying to create a pre-example to show it will work. Can someone quickly see what dumb thing I am forgetting?

<div ng-controller="MyCtrl">
    <form name="myForm">
      <div ng-repeat="item in items track by $index">
          <input type="text" ng-model="item.a">
          <input type="text" ng-model="item.b">
          <input type="text" ng-model="item.c">
          <label>Total: </label><label ng-bind="total(item)"></label>
      </div>
    </form>
    <div>
    <label>Grand Total: </label><label ng-bind="grandTotal()"></label>
    </div>
</div>

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

myApp.controller('MyCtrl', function($scope) {
        $scope.items = [
      {
        a: 0, b: 0, c: 0
      },
      {
        a: 0, b: 0, c: 0
      }];

    $scope.total = function(item) { 
        var result = item.a * item.b * item.c;

      return isNaN(result) ? 0 : result;
    };

    $scope.grandTotal = function() { 
        var result = 0;

      angular.forEach($scope.items, function(item) {
        result += $scope.total(item);
      });

      return isNaN(result) ? "" : result.toString();
    };
});

2 Answers 2

1

ng-bind should be without $scope. You don't need to mention $scope in view bindings, it directly refers to $scope/this(context) of controller.

Other than that additionally change all input's ng-bind to ng-model to enable two way binding over all input fields.

Markup

<input type="text" ng-model="item.a">
<input type="text" ng-model="item.b">
<input type="text" ng-model="item.c">

ng-bind="total(item)"

Forked JSFiddle

Sign up to request clarification or add additional context in comments.

5 Comments

Good catch, but even with $scope removed, I don't see it displaying the totals
He should change the ng-bind to ng-model for his <input>. Add this to your answer.
I updated fiddle jsfiddle.net/Lhkedykz/15. It still doesn't work. It calls my total function at the start but never again after I start typing in values.
Zach please write up answer and I will mark it answer.
@Zach Thanks for heads up as well. after answering I got busy with something else. And then I edited comment & saw fiddle. Thereafter I realize about ng-bind are there on input fields.. Thank you once again :)
1

Use

<input type="text" ng-model="item.a">

instead of

<input type="text" ng-bind="item.a">

Updated fiddle http://jsfiddle.net/Lhkedykz/17/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.