我是AngularJS的新手(从Udemy课程中学习)。我试图通过使用来分离函数(有点像Java中的类),所以我使用多个服务。不知何故从控制器工作调用,但从另一个服务渲染调用
“HelperFunctions未定义
at Object.groceryService.getNewId (app.js:57)"
错误。
它引用的行在“GroceryService”中:
var maxID = HelperFunctions.findMaxID(groceryService.groceryItems);
虽然以下行正常,但只要它在控制器中:
的console.log(HelperFunctions.test);
我的参考代码:
var app = angular.module('groceryListApp', ["ngRoute"]);
app.controller("GroceryListItemsController", ["$scope", "$routeParams", "$location", "GroceryService", "HelperFunctions", function($scope, $routeParams, $location, GroceryService, HelperFunctions){
$scope.groceryItems = GroceryService.groceryItems;
console.log(HelperFunctions.test);
$scope.groceryItem = { id:7, completed:true, itemName: "cheese", date: new Date() };
$scope.save = function(){
GroceryService.save($scope.groceryItem);
$location.path("/");
}
}]);
app.service("HelperFunctions", function(){
var findMax = {};
findMax.test = 7;
findMax.findMaxID = function(arrayOfGroceries){
var max = -1;
for(i=0;i<arrayOfGroceries.length;i++)
{
if(arrayOfGroceries[i]>max)
{
max = arrayOfGroceries[i].id;
}
}
console.log("a");
return max;
}
return findMax;
});
app.service("GroceryService", function(){
var groceryService = {};
groceryService.groceryItems= [
{id: 1, completed: true, itemName: 'milk', date: '2014-10-01'}, {id: 2, completed: true, itemName: 'cookies', date: '2014-10-01'},
{id: 3, completed: true, itemName: 'ice cream', date: '2014-10-02'}, {id: 4, completed: true, itemName: 'potatoes', date: '2014-10-02'},
{id: 5, completed: true, itemName: 'cereal', date: '2014-10-03'}, {id: 6, completed: true, itemName: 'bread', date: '2014-10-03'},
{id: 7, completed: true, itemName: 'eggs', date: '2014-10-04'}, {id: 8, completed: true, itemName: 'tortillas', date: '2014-10-04'} ]
groceryService.getNewId = function(){
if(groceryService.newId){
groceryService.newId++;
console.log("A" + groceryService.newId);
return groceryService.newId;
}
else{
var maxID = HelperFunctions.findMaxID(groceryService.groceryItems);
groceryService.newId = maxID + 1;
console.log("B" + groceryService.newId);
return groceryService.newId;
}
}
groceryService.save = function(entry){
entry.id = groceryService.getNewId();
groceryService.groceryItems.push(entry);
};
return groceryService;
});
此后还有路由,但我认为这是无关紧要的,对吧?
答案 0 :(得分:1)
未定义HelperFunctions,因为您尚未将其注入GroceryService。
这篇文章应该引导您朝着正确的方向前进:Injecting a service into another service in angularJS。