无法检索ng-model的值(与ng-repeat一起使用)

时间:2016-04-14 04:56:00

标签: javascript angularjs

成为角度js的新手,只是尝试一些基本的例子&遇到了这个问题。

我正在使用ng-repeat创建一个表,其中json array是数据源。该表有一个数量列和一个添加按钮。

一旦我点击添加按钮,我想增加数量的值。理解是因为它是双向数据绑定,如果我将值绑定增加到ng-model它将反映在视图中,< em>哪个没有发生

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

我遵循了这个link,但仍无法解决问题。

我创建了这个Plunker,这有助于理解这个问题。

2 个答案:

答案 0 :(得分:1)

试试这样。你应该改变你的解决方案。我将bookId作为参数传递给函数,当动作执行时,再加上数组中的bookQuantity字段。

// 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>

答案 1 :(得分:0)

试试这个: - *.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;
}