计算点击次数并添加到输入

时间:2017-02-21 08:20:07

标签: angularjs

首先,我是Angular JS的新手。

我有一个项目列表,通过点击每个项目,它应该被添加到表格中。这些项目存储在json文件中。

如果点击事件重复多次,则表格上的计数器输入必须增加。

<ul class="list-inline" >
<li ng-repeat="food in foods" class="food_list">

<img class="img-box" src="images/{{ food.food_photo }}" ng-click = 'addRow(food)'><br/><span>{{food.food_name}}</span>

 </li>
 </ul>

<table class="table" id="table-right">
<tr>
    <th>Item Name</th>
    <th>Quantity</th>
    <th>Price</th>
    <th class="hidden-print">Delete</th>
</tr>

<tr ng-repeat="row in rows">
<td>{{row.food_name}}</td>
<td><input type="number" class="form-control"  ng-model="row.food_count"></td>
<td>{{row.food_cost}}</td>
<td class="hidden-print"><button class="btn btn-info hidden-print"  data-ng-click="removeRow($index)">Remove</button></td>
</tr>

app = angular.module('app',[]);
app.controller('MyCtrl', ['$scope','$http', function($scope, $http){

$scope.rows = [];

$scope.addRow = function(obj) {

    $scope.foodname = obj.id;
    $scope.foodprice = obj.price;

    $scope.rows.push(obj);

    $scope.counter++;
}

}]);
你能帮帮我吗?谢谢。

1 个答案:

答案 0 :(得分:1)

首先,您必须了解food_count对象的row属性是应该在重复点击时更新的变量。更新任何其他$scope变量不会更改行特定数据,因为您的视图绑定到$scope.rows对象。

您的addRow功能应如下所示。

$scope.addRow = function(obj) {
      if($scope.rows.indexOf(obj) >= 0){ // if this obj already exist
         $scope.rows[$scope.rows.indexOf(obj)].food_count++;    
      }
      else
         $scope.rows.push(obj);
   } 

然后$scope.foods的对象应该有一个名为food_count的属性来显示。

$scope.foods = [
        {food_name:'Jani',food_cost:'10', food_count:0},
        {food_name:'Hege',food_cost:'8',food_count:0},
        {food_name:'Kai',food_cost:'5',food_count:0}]

solution