我怎样才能观察更改服务中的数组元素?
例如,我们有一些CartController
和ProductListService
。
在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
。数量变化。那我怎么能这样做呢?
由于
答案 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();
}
}
})();