我正在尝试创建一个工厂,并在每个控制器中使用它跨越路线,但显然我做错了...
该应用:
var app = angular.module('sam', ['ngRoute', 'ngGrid', 'ui.bootstrap']);
工厂
app.factory("User",function(){
return {};
});
路线
// configure our routes
app.config(function($routeProvider) {
$routeProvider
// route for the main page which will direct to the buildings page
.when('/', {
templateUrl : 'web/pages/buildings.html',
controller : 'mainController',
controllerAs : 'buildings'
})
});
控制器
app.controller('mainController', ['$filter', '$http','$log', function($filter, $http, $log, User){
$log.log('hello!!!!!', User);
}]);
打印:hello!!!!! undefined
答案 0 :(得分:2)
你错过了'用户'在你的控制器中。
app.controller('mainController', ['$filter', '$http','$log', **'User',** function($filter, $http, $log, User){
$log.log('hello!!!!!', User);
}]);
答案 1 :(得分:1)
您忘记将User
作为注入数组的一部分
controller('mainController', ['$filter', '$http','$log', function($filter, $http, $log, User){
应该是:
controller('mainController', ['$filter', '$http','$log','User', function($filter, $http, $log, User){
答案 2 :(得分:0)
app.factory("User",function(){
return {
show:function(){
alert('Factory called')
}
};
});
app.controller('mainController', ['$filter', '$http','$log','User', function($filter, $http, $log, User){
//that is the way you can call your factory
// you can call this factory function in any controller by injecting it.
User.show(); //will popup alert window.
}]);