如何从单独的产品控制器更新此Angular购物车?

时间:2014-12-04 02:17:47

标签: angularjs

我推车工作但我似乎无法弄清楚如何从单独的产品控制器正确地将商品添加到购物车。我一直在玩服务和工厂,但我无法理解如何让它们发挥作用。

http://jsfiddle.net/75m7e/823/

HTML

<h2>Shopping Card Example</h2>
<div ng:controller="CartForm">
    <table class="table">
        <tr>

            <th>Description</th>
            <th>Qty</th>
            <th>Cost</th>
            <th>Total</th>
            <th></th>
        </tr>
        <tr ng:repeat="item in invoice.items">
            <td><input type="text" ng:model="item.description"class="input-small"></td>           
            <td><input type="number" ng:model="item.qty" ng:required class="input-mini"></td>
            <td><input type="number" ng:model="item.cost" ng:required class="input-mini"></td>
            <td>{{item.qty * item.cost | currency}}</td>
            <td>
                [<a href ng:click="removeItem($index)">X</a>]
            </td>
        </tr>
        <tr>
            <td><a href ng:click="addItem()" class="btn btn-small">add item</a></td>
            <td></td>
            <td>Total:</td>
            <td>{{total() | currency}}</td>
        </tr>
    </table>
</div>

的JavaScript

function CartForm($scope) {
$scope.invoice = {
    items: [{
        qty: 10,
        description: 'item',
        cost: 9.95}]
};

$scope.addItem = function() {
    $scope.invoice.items.push({
        qty: 1,
        description: '',
        cost: 0
    });
},

$scope.removeItem = function(index) {
    $scope.invoice.items.splice(index, 1);
},

$scope.total = function() {
    var total = 0;
    angular.forEach($scope.invoice.items, function(item) {
        total += item.qty * item.cost;
    })

    return total;
}
}

我想单击产品控制器中的“添加到购物车”按钮,并将产品数据公开给购物车控制器,将该项目添加到列表中。最好的方法是什么?

0 个答案:

没有答案