我正在使用普通控制器来制作购物车系统和 $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>
购物车.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
});
};
});
索引.php
<body ng-app="alice">
<div ng-view></div> <!-- Goes to main.html using route-->
</body>
页眉.html
<div ng-include src="'view/cart.html'">