1

Being new in angular js ,just trying some basic example & came across this issue.

I am creating a table using ng-repeat where a json array is the data source. The table has a quantity column and an add button.

I want to increase the value of quantity once I click on the add button.By understanding is since it is a two way data binding if I increase the value bind to ng-model it will reflect in the view, which is not happening

JS

angular.module('DemoApp',[]).controller('TableController',['$scope',function($scope){
  $scope.dataset = [json data ];
      $scope.add = function($event){
        // get $scope.bookQuantity,add 1
        var _m =$scope.bookQuantity;
        console.log(_m) // consoling undefined;
      }
    }])

I followed this link but still not able to resolve the issue.

I have created this Plunker which may help to understand the problem.

Community
  • 1
  • 1
brk
  • 48,835
  • 10
  • 56
  • 78

2 Answers2

1

try like this. you should change your solution for this. i pass bookId as parameter to function and when action do it plus bookQuantity field in array.

// Code goes here

angular.module('DemoApp',[]).controller('TableController',['$scope',function($scope){
  
  $scope.dataset = [{
bookId: "1001",
bookName: "Wings",
bookPrice: 224,
bookQuantity: 4
    },{
bookId: "1002",
bookName: "Turning",
bookPrice: 142,
bookQuantity: 3
},{
bookId: "1003",
bookName: "Playing",
bookPrice: 402,
bookQuantity: 2
},{
bookId: "1004",
bookName: "Steve Jobs",
bookPrice: 418,
bookQuantity: 2},{
bookId: "1005",
bookName: "History",
bookPrice: 207,
bookQuantity: 2
}]
  
  $scope.add = function(bookId){
    angular.forEach( $scope.dataset,function(item){
      
        if(item.bookId == bookId)
          item.bookQuantity = item.bookQuantity + 1;
      });
    
    console.log($scope.dataset);
  }
  
  
  
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
 <div ng-app="DemoApp" ng-controller ="TableController" >
    <table>
      <thead></thead>
      <tbody>
        <tr ng-repeat="data in dataset">
          <td>{{data.bookId}}</td>
          <td>{{data.bookName}}</td>
          <td>{{data.bookPrice}}</td>
          <td>{{data.bookQuantity}}</td>
          <td><input type = "button" value ="Add" data-id ="{{data.bookId}}" ng-click = "add(data.bookId)"></td>
          </tr>
      </tbody>
      
      
      
      </table>
    </div>
Hadi J
  • 16,989
  • 4
  • 36
  • 62
0

try this :- *.html

<thead></thead>
  <tbody>
    <tr ng-repeat="data in dataset">
      <td>...</td>
      ...
      .
      <td><input type = "button" value ="Add" data-id ="{{data.bookId}}" ng-click = "add(data)"></td>
      </tr>
  </tbody>

*.js

$scope.add = function(record){
   record.bookQuantity  = record.bookQuantity + 1;
   console.log(record.bookQuantity); // consoling not undefined;
}
manish
  • 1,450
  • 8
  • 13