gpt4 book ai didi

javascript - 当我们切换到 Angular js中的其他 View 时如何获取购物车值

转载 作者:行者123 更新时间:2023-12-03 12:28:11 25 4
gpt4 key购买 nike

您好,我正在开发一个购物车项目。

它有不同的类别。

每个类别都有不同的产品。

当我将特定类别的产品添加到购物车时,它就会被添加。

当我返回并将另一个产品添加到同一类别的购物车时,它已正确添加,并且前一个产品也显示良好。

但是,当转到另一个类别并将产品添加到购物车时,购物车页面会清除所有以前的产品,并且不会显示任何以前的产品。

如何解决此问题并维护添加到购物车中但未在整个项目中清除的产品。

我没有使用任何服务来维护它,我只想在 angularjs 中维护它

最佳答案

只有两种方法可以在 Angular 摘要周期内的所有 Angular 应用程序中保存数据。

    1--$rootScope(not recommended)
2--using Angular Services

因为你的评论我在推断你说“我没有使用任何服务来维护它,我只想在 angularjs 中维护它”您正在引用第三方或后端服务。 Angular 有自己的一套服务,您也可以使用,即 cookie 服务、存储服务,或者您可以推出自己的运输车服务(这就是建议),构建您的购物卡服务来处理您的所有操作并跟踪您的数据。 Angular 服务是应用程序的单例对象,允许它们保存数据。创建服务非常简单,您可以这么说

app.service('myservice',['$rootScope','$http','$timeout',function($rootScope,$http,$timeout){
//$rootscope useful if you want to broadcast events to the app
//$http useful if you want to update based on the users selection or deletion
//$timeout useful if you want to set time based alerts or expirations
var storage={};
return{
insert:function(item){/*logic to insert an item into storage*/},
remove:function(id){/*logic to remove an item from storage*/},
get:function(id){/*logic to get all items*/}
}
}])

使用服务的控制者

app.Controller('Category1ItemsController',['myservice',function(myservice){
$scope.items=[1,2,3,4,5,6]
$scope.appendItem=function(item){
myservice.insert(item);
}
}]);

使用 Controller 的 View

<ul ng-controller="Category1ItemsController">
<li ng-repeat="item in items">
{{item}}
<button ng-click="appendItem(item)">Add</button>
</li>
</ul>

这样的事情可能会让你更清楚。您使用什么生成器/模板项目?

关于javascript - 当我们切换到 Angular js中的其他 View 时如何获取购物车值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24073983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com