服务中的角度监视数组项

时间:2014-12-01 12:16:29

标签: javascript angularjs angularjs-scope

我怎样才能观察更改服务中的数组元素?

例如,我们有一些CartControllerProductListService

ProductListService我们提取项目:

/**
 * Fetch all the products in user cart
 *
 * @return void
 */
this.all = function() {
    $http
        .get('/api/cart/all.php')
        .success(function(resp) {
            _this.products = resp.products;
        });
};

getter

/**
 * Getter for all user products
 *
 * @return array
 */
this.getProducts = function() {
    return _this.products;
};

在我们的controller

$scope.getProducts = function() {
    return ProductListService.getProducts();
};

并且在视野中:

<div class="price">
    <span ng-click="removeOne(product)">—</span>
    <input type="text" ng-model="product.PRODUCT.QUANTITY">
    <span ng-click="addOne(product)">+</span>
</div>

因此,我们预期的结果是一个带有+/-按钮的简单购物车,并输入数量类型。

当我们点击这些图标+/-时,我们正在触发addOne/removeOne方法(他们正在执行此操作ProductListService.quantity(id, quantity);

但是当我们改变<input>的价值时 - 没有任何反应,因为我无法观察它的变化。

我的最大想法是观察我们products中的整个service

// Here we will update product quantity on user input
$scope.$watch(
    function() {
        return ProductListService.products;
    }, 
    function(products, old) {
        // products will be full products list (not single product)
        // Here a lot of loops to determine what product quantity was changed
    },
    true
);

目标是观看ProductListService.products。数量变化。那我怎么能这样做呢?

由于

1 个答案:

答案 0 :(得分:0)

我建议你这样做:

//HTML
<div ng-controller="ProductController as prodCtrl">
    <div class="productList" ng-repeat="product in prodCtrl.products">
        <div class="price">
                <span ng-bind="product.Name"></span>
                <span ng-click="prodCtrl.removeOne(product)">—</span>
                <input type="text" ng-model="product.Quantity">
                <span ng-click="prodCtrl.addOne(product)">+</span>
        </div>
    </div>
</div>

//CONTROLLER
(function () {
    'use strict';

    angular
        .module('app')
        .controller('ProductController', ProductController);

    ProductController.$inject = ['$scope', 'ProductListService'];

    function ProductController($scope, ProductListService) {
        /* jshint validthis:true */

        $scope.removeOne = function (product) {
           //do whatever - product.Quantity is bound to your text box, no need to watch
           ProductListService.quantity(product.Id, product.Quantity)
        };
        $scope.addOne = function (product) {
           //do whatever - product.Quantity is bound to your text box, no need to watch
           ProductListService.quantity(product.Id, product.Quantity)
        };

    activate();

    function activate() {
         $scope.products=ProductListService.getProducts();
    }
    }
})();