0

I'm trying to create a factory and use it cross routes in each controller but apparently I'm doing something wrong...

The app:

var app = angular.module('sam', ['ngRoute', 'ngGrid', 'ui.bootstrap']);

The factory

app.factory("User",function(){
        return {};
    });

The routes

// 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'
            })

    }); 

The controller

app.controller('mainController', ['$filter', '$http','$log', function($filter, $http, $log, User){
        $log.log('hello!!!!!', User);
}]);

This prints : hello!!!!! undefined

omer bach
  • 2,345
  • 5
  • 30
  • 46

3 Answers3

2

you are missing 'User' in your controller.

app.controller('mainController', ['$filter', '$http','$log', **'User',** function($filter, $http, $log, User){
        $log.log('hello!!!!!', User);
}]);
mmohab
  • 2,303
  • 4
  • 27
  • 43
alfcho
  • 61
  • 1
  • 4
1

You forgot to include User as part of injection array

controller('mainController', ['$filter', '$http','$log', function($filter, $http, $log, User){

Should be:

controller('mainController', ['$filter', '$http','$log','User', function($filter, $http, $log, User){
charlietfl
  • 170,828
  • 13
  • 121
  • 150
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.

}]);

micronyks
  • 54,797
  • 15
  • 112
  • 146