Search code examples
javascriptangularjsdata-bindingangular-ngmodelng-bind

Dynamic form Angular issue


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();
    };
});

Solution

  • 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