2013-12-17 47 views
1

我想添加對象到$ scope.orderitems,如果對象已經在$ scope.orderitems中我想更改數量屬性的對象使用angular.forEach而不是添加另一個對象。每當我調用additem函數時,我都會遇到一個錯誤,那就是沒有定義orderitems。如何檢測一個對象是否已被添加使用angular.forEach AngularJS

這裏是我的代碼

HTML

<input type="text" ng-model="item.name"> 
<button type="button" ng-click="additem(item)"> 

<ul> 
    <li ng-repeat="orderitem in orderitems"> 
     <p>{{ orderitem.name }} | {{ orderitem.qty }}</p> 
    </li> 
</ul> 

JS

app.controller('OrderCtrl', function($scope) { 
    $scope.orderitems = []; 
    $scope.additem = function(data) { 

     angular.forEach(orderitems, function(orderitem) { 
      if (orderitem.id === data.id) { 
       orderitem.qty = orderitem.qty++; 
      } else { 
       data.qty = 1; 
       $scope.orderitems.push(data); 
      } 
     }); 
    }; 
}); 
+1

'angular.forEach($ scope.orderitems,功能(OrderItem的......' – calebboyd

回答

7

這裏的工作小提琴:http://jsfiddle.net/rodhartzell/hbN4G/

HTML

<body ng-app="app"> 
    <div ng-controller="OrderCtrl"> 
    <input type="text" ng-model="item.name"> 
     <button type="button" ng-click="additem()">add</button> 

    <ul> 
     <li ng-repeat="orderitem in orderitems"> 
      <p>{{ orderitem.name }} | {{ orderitem.qty }}</p> 
     </li> 
    </ul> 
</div> 

控制器

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

app.controller('OrderCtrl', function($scope) { 

    $scope.orderitems = [{name: 'foo', id:1, qty:1}]; 
    $scope.additem = function() { 
     var exists = false; 
     var data = { 
      id : $scope.orderitems.length + 1, 
      name: $scope.item.name, 
      qty: 1 
     } 
     angular.forEach($scope.orderitems, function (item) { 
      if (item.name == data.name) { 
       exists = true; 
       item.qty++; 
       return false; 
      } 
     }); 
     if(!exists){ 
      $scope.orderitems.push(data); 
     } 

    }; 
}); 
0
$scope.orderitems = []; 
$scope.additem = function(data) { 
    var item = null 
    angular.forEach(orderitems, function(orderItem) { 
     if (orderItem.id === data.id) { 
      item = orderItem 
      return false; 
     } 
    }); 
    if (item == null) { 
     item = { 
     id: data.id, qty : 0 
     } 
     $scope.orderitems.push(item) 
    } 

    item.qty++ 
}; 
相關問題