如何使用angular.forEach AngularJS检测是否添加了对象

时间:2013-12-17 20:13:51

标签: javascript arrays angularjs foreach

我正在尝试向$ scope.orderitems添加对象,如果对象已经在$ scope.orderitems中,我想使用angular.forEach更改对象的quantity属性,而不是添加另一个对象。每当我调用additem函数时,我都会收到一个错误,即未定义orderitems。

这是我的代码

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

2 个答案:

答案 0 :(得分: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>

CONTROLLER

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

    };
});

答案 1 :(得分: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++
};