【发布时间】:2018-05-13 21:22:36
【问题描述】:
我正在使用普通控制器来制作购物车系统和 $ngcookies。一切正常,但我的数据(.name)仅在浏览器刷新/重新加载后才显示在购物车上,老实说主要 HTML 和 Cart.html 在不同的控制器/视图($ngroute)中。我有什么错误来解决这个问题吗? 任何帮助将不胜感激。
我希望我的数据在点击时而不是在刷新后显示(实时)
HTML
<div ng-controller="AliceController" class="talent-container">
<div ng-repeat="talent in talents">
<button type="button" href="#" ng-click="addItemToCart(talent)"></button>
<div id="name">{{talent.name}}</div>
</div>
</div>
cart.html
<div>
<ul class="userset" ng-show="cart.length !== 0">
<li ng-repeat="c in cart">
<h6>{{c.name}}</h6>
</li>
</ul>
</div>
模块
var alice = angular
.module('alice', ['ngRoute', 'angular-carousel', 'ngTouch', 'angular-carousel.shifty', 'ngCookies'])
控制器
.controller('AliceController', ['$scope', '$http', '$location', '$cookies', function ($scope, $http, $location, $cookies) {
$http.get('api.php').
then(function (res) {
$scope.talents = res.data.talents;
// cart
$scope.cart = [];
$scope.total = 0;
if (!angular.isUndefined($cookies.get('total'))) {
$scope.total = parseFloat($cookies.get('total'));
}
//Sepetimiz daha önceden tanımlıysa onu çekelim
if (!angular.isUndefined($cookies.get('cart'))) {
$scope.cart = $cookies.getObject('cart');
}
$scope.addItemToCart = function (talent) {
if ($scope.cart.length === 0) {
talent.count = 1;
$scope.cart.push(talent);
} else {
var repeat = false;
for (var i = 0; i < $scope.cart.length; i++) {
if ($scope.cart[i].id === talent.id) {
repeat = true;
$scope.cart[i].count += 1;
}
}
if (!repeat) {
talent.count = 1;
$scope.cart.push(talent);
}
}
var expireDate = new Date();
expireDate.setDate(expireDate.getDate() + 1);
$cookies.putObject('cart', $scope.cart, {
'expires': expireDate
});
$scope.cart = $cookies.getObject('cart');
$cookies.put('total', $scope.total, {
'expires': expireDate
});
};
$cookies.put('total', $scope.total, {
'expires': expireDate
});
};
});
index.php
<body ng-app="alice">
<div ng-view></div> <!-- Goes to main.html using route-->
</body>
Header.html
<div ng-include src="'view/cart.html'">
【问题讨论】:
-
cart.html 在哪个范围内?我的意思是 cart.html 的控制器/ng-congtroller 是什么
-
@RonitMukherjee cart.html 不在任何范围/控制器中。它只是来自 ng-include 的一个页面。但在 cart.html 我把 ng-controller="AliceController" 放在父 div 中。
-
我猜当您再次为 cart.html 提及 ng-controller 时,它会再次重新运行控制器代码,因此
the $scope.cart = []; $scope.total = 0;再次运行并重置值。尝试在控制台中打印一些东西。希望您能看到两次消息。告诉我。 -
@RonitMukherjee 它只打印 1 个字符串 `console.log('apakek');' .当我在 cart.html 中删除控制器时,即使我重新加载浏览器也不会显示任何数据。
-
能否也分享一下 HTML 部分?您在哪里包含了 cart.html
标签: html angularjs cart ng-controller angular-cookies