【发布时间】:2014-02-17 16:40:10
【问题描述】:
我是 AngularJS 的新手,我正在尝试修改 http://www.codeproject.com/Articles/576246/A-Shopping-Cart-Application-Built-with-AngularJS 的示例
我在示例中实现了一个新的支付服务来调用我的服务器上的 Json 方法,它工作正常,但是当我调用方法 clearItems();要在成功时从购物车中删除项目,它会在后台按预期删除项目(正如我从刷新页面和购物车中看到的那样) - 我的问题是它没有清除 UI 中的购物车(不刷新)
如果我调用 this.clearItems();在 Json 调用之后,它会按预期清除 UI 中的购物车项目,但这不是我需要的,因为我只想在成功后清除这些项目。
谁能建议我如何让它工作?
下面列出了我的 Json 调用
var me = this;
//this.clearCart = clearCart == null || clearCart;
$.ajax({
cache: false,
type: "POST",
url: '/pos/JsonCashPayment',
contentType: 'application/json',
dataType: "json",
data: JSON.stringify(this.items),
success: function (data) {
me.clearItems();
alert('success function called');
// Do something with the returned data
// This can be any data
}
});
//this.clearItems();
谢谢
标记
编辑 - 运行 $http 的问题
关于马克的建议,我知道要做到这一点,我需要使用 $http 而不是 $json。这样做的问题是我需要在通过 app.js 附加到控制器的 shoppingCart.js 类(作为支付部分的一部分)中执行此操作(代码如下)。当我尝试这个时,虽然我得到一个 $http 不存在的 JS 错误。
有没有办法使用来自 shoppingCart.js 类的 $http?
app.js
var storeApp = angular.module('AngularStore', []).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/store', {
templateUrl: 'POS/store',
controller: storeController
}).
when('/products/:productSku', {
templateUrl: 'POS/product',
controller: storeController
}).
when('/cart', {
templateUrl: 'POS/shoppingCart',
controller: storeController
}).
otherwise({
redirectTo: '/store'
});
}]);
// create a data service that provides a store and a shopping cart that
// will be shared by all views (instead of creating fresh ones for each view).
storeApp.factory("DataService", function ($http) {
// create store
var myStore = new store($http);
// create shopping cart
var myCart = new shoppingCart("AngularStore");
controller.js
function storeController($scope, $http, $routeParams, DataService) {
// get store and cart from service
$scope.store = DataService.store;
$scope.cart = DataService.cart;
shoppingCart.js
function shoppingCart(cartName) {
this.cartName = cartName;
this.clearCart = false;
this.checkoutParameters = {};
this.items = [];
// load items from local storage when initializing
this.loadItems();
// save items to local storage when unloading
var self = this;
$(window).unload(function () {
if (self.clearCart) {
self.clearItems();
}
self.saveItems();
self.clearCart = false;
});
}
shoppingCart.prototype.checkoutCash = function (parms, clearCart, $scope, $http) {
// Need to be able to run $http here
$http({
url: '/pos/JsonCashPayment',
method: "POST",
data: this.items,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (data, status, headers, config) {
}).error(function (data, status, headers, config) {
});
}
【问题讨论】:
-
请使用角度构造 $resource 或 $http。否则,您需要使用
$scope.$apply()方法告诉 Angular 模型更新。 -
你能告诉我怎么做吗?可以从不是控制器的 shoppingCart.js 文件中完成吗?我可以从该文件访问 $resource 或 $http 吗?
标签: javascript jquery json angularjs