你能帮我找到这段代码的错误,它说" foodFactory没有定义"。我还在学习angularjs所以可能有错误,但我试图使用路线+工厂。
var foodApp = angular.module("foodApp", ["ngRoute"]);
foodApp.config(function($routeProvider)
{
$routeProvider
.when('/',
{
controller: 'foodController',
templateUrl: '/routes/view1.html'
})
.when('/view2',
{
controller: 'foodController',
templateUrl: '/routes/view2.html'
})
.when('/view3',
{
controller: 'foodController2',
templateUrl: '/routes/view3.html'
})
.otherwise
({ redirectTo: '/' });
});
foodApp.factory("foodFactory", function()
{
var foods = [
{name: "Bread"},
{name: "Cheese"},
{name: "Blackberries"}
];
var factory = {};
factory.getFoods = function ()
{
return foods;
};
return factory;
});
var controllers = {};
controllers.foodController = function($scope)
{
$scope.foods = foodFactory.getFoods();
$scope.foods2 = foodFactory.getFoods();
};
controllers.foodController2 = function($scope)
{
$scope.foods = foodFactory.getFoods();
};
foodApp.controller(controllers);
view1.html,view2.html和view3.html - 很好,路线也在运作,但它不会从工厂返回食物阵列。
答案 0 :(得分:6)
controllers.foodController = function($scope,foodFactory) // you need to inject foodFactory
{
$scope.foods = foodFactory.getFoods();
$scope.foods2 = foodFactory.getFoods();
};
controllers.foodController2 = function($scope,foodFactory) // you need to inject foodFactory
{
$scope.foods = foodFactory.getFoods();
};