我是AngularJS的新手。我正在做Adam Freeman的Pro AngularJS書中的一個例子,但被這個錯誤困住了。
Error: [$injector:pget] Provider 'function()' must define $get factory method.
我現在要創建購物車小工具和摘要部分視圖。當AngularJS試圖加載Cart模塊時,會引發上述錯誤。
以下是來自Chrome開發人員工具的部分錯誤消息。作者在這一點上沒有提及關於$ get函數或提供者的任何信息。不知道我在做什麼錯。請幫忙。
Uncaught Error: [$injector:modulerr] Failed to instantiate module sportsStore due to:
Error: [$injector:modulerr] Failed to instantiate module cart due to:
Error: [$injector:pget] Provider 'function()' must define $get factory method.
http://errors.angularjs.org/1.2.23/$injector/pget?p0=function%20()
購物車小部件代碼。
angular.module("cart", [])
.factory(function() {
var cartData = [];
return {
addProduct: function (id, name, price) {
var addedToExistingItem = false;
for (var i = 0; i < cartData.length; i++) {
if (cartData[i].id == id) {
cartData[i].count++;
addedToExistingItem = true;
break;
}
}
if (!addedToExistingItem) {
cartData.push({
count: 1, id: id, price: price, name: name
});
}
},
removeProduct: function (id) {
for (var i = 0; i < cartData.length; i++) {
if (cartData[i].id == 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;
}
}
}
});
這裏是它是如何充分利用app.html
<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>
....
<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="/sportsstore/app.html" class="alert-link">Click here to try again</a>
</div>
<ng-include src="'views/productList.html'" />
</body>
SportsStore模塊代碼調用..
angular.module("sportsStore")
.constant("dataUrl", "http://localhost:5500/products")
.controller("sportsStoreCtrl", function ($scope, $http, dataUrl) {
$scope.data = {}
$http.get(dataUrl)
.success(function (data) {
$scope.data.products = data;
})
.error(function (error) {
$scope.data.error = error;
});
});
你可以發佈模塊sportstore的代碼? – sma 2014-10-09 19:18:54
增加了sportsStore模塊代碼。 – Pak 2014-10-09 19:22:48
我在做一個愚蠢的錯誤。我錯過了下面函數調用的第一個參數。 .factory(「cart」,function()。但是當我發佈這個問題時,我從我的應用程序中的錯誤位置拿來了,這是對的,我真的很抱歉,我會更新發布的代碼,以便它反映正確的問題 – Pak 2014-10-09 19:56:34