我正在完成Adam Freeman撰写的Pro AngularJS一书,在第7章中,在为购物车创建小部件时,它不会像导演那样在导航栏中呈现。我已经进行了比较,甚至回过头来将所提供的源代码粘贴到我的两个方面,小部件仍然无法呈现,(<cart-summary />
是哪里,但其他一切都是。我已经检查了这本书的勘误并没有发表任何内容,所以我完全陷入了这一点。我有一种感觉,这可能是那些看起来正确的事情,但我没有运气提前谢谢!这是我的代码:
-app.html文件:
<!DOCTYPE html>
<html lang="en" ng-app="sportsStore">
<head>
<title>SportsStore</title>
<script src="angular.js"></script>
<link rel="stylesheet" href="bootstrap.css">
<link rel="stylesheet" href="bootstrap-theme.css">
<script>
angular.module("sportsStore", ["customFilters", "cart"]);
</script>
<script src="controllers/sportsStore.js"></script>
<script src="filters/customFilters.js"></script>
<script src="controllers/productListControllers.js"></script>
<script src="components/cart/cart.js"></script>
</head>
<body ng-controller="sportsStoreCtrl">
<div class="navbar navbar-inverse">
<a class="navbar-brand" href="#">SPORTS STORE</a>
<cart-summary />
</div>
<div class="alert alert-danger" ng-show="data.error">
Error ({{ data.error.status }}). The product was not loaded. <a href="/app.html" class="alert-link">Click here to try again</a>
</div>
<ng-include src="'views/productList.html'"></ng-include>
</body>
</html>
-views / cartSummary.html文件:
<style>
.navbar-right { float: right !important; margin-right: 5px; }
.navbar-text { margin-right: 10px; }
</style>
<div class="navbar-right">
<div class="navbar-text">
<b>Your Cart:</b>
{{ itemCount() }} item(s),
{{ total() | currency }}
</div>
<a class="btn btn-default navbar-btn">Checkout</a>
</div>
-components / cart / cart.js文件:
angular.module("cart", [])
.factory("cart", function () {
var cartData =[];
return {
addProduct: function(id, name, price) {
var addedToExistingItem = false;
for (var i = 0; i < cartData.length; i++) {
if (cartData[i].objectId == id) {
cartData[i].count++;
addedToExistingItem = true;
break;
}
}
if (!addedToExistingItem) {
cartData.push({
count: 1, objectId: id, price: price, name: name
});
}
},
removeProduct: function(id) {
for (var i = 0; i <cartData.length; i++) {
if (cartData[i].objectId == id) {
cartData.splice(i, 1);
break;
}
}
},
getProducts: function () {
return cartData;
}
};
})
.directive("cartSummary", function(cart) {
return {
restrict: "E",
templateUrl: "components/cart/cartSummary.html",
controller: function ($scope) {
var cartData = cart.getProducts();
$scope.total = function () {
var total = 0;
for (var i = 0; i < cartData.length; i++) {
total += (cartData[i].price * cartData[i].count);
}
return total;
};
$scope.itemCount = function () {
var total = 0;
for (var i =0; i <cartData.length; i++) {
total += cartData[i].count;
}
return total;
};
}
};
});
答案 0 :(得分:0)
我发现了问题!作者采用了通过任务放置应用程序部分的方法,因此是“components”目录,当我创建cartSummary.html文件时,我意外地将它放在“views”目录中,包含所有其他部分。一旦我从“views”目录中删除它并将其放在“cart”目录中,它就会正确显示。经验教训!
答案 1 :(得分:0)
cartData.push({count: 1, objectId: id, price: price, name: name});
将templateUrl从原来的' components / cart / cartSummary.html '更改为' views / cartSummary.html '后,它终于有效了