angularjsangularjs-module

passing angular services through modules


I am looking at the code of HotTowel-Angular and I am trying to make a small example using it but I can't get it to work.

This is my code:

var app = angular.module('myApp', ['common']);

var common = angular.module('common', []);

common.factory('commonf', ['$rootScope', '$timeout', commonFactory]);



function commonFactory($rootScope, $timeout){

    var service = {
    $rootScope: $rootScope,
    $timeout: $timeout
    }

    return service;

}

app.controller('TestCtrl', ['commonf', testctrl]);

function testctrl(commonf) {

   activate(); 

   var $timeout = commonf.$timeout;

   function activate() {

     $timeout(function () {
     alert("test");
     }, 5);

   }

}

The idea is to keep all common angular services that are used throughout the app inside a service which is injected to all services/controllers.

When I try to do this above I get the following error:

"$timeout is not a function";

Edit: Plunker


Solution

  • You are calling activate() before you pulled the dependency from commonf. Change to this:

    function testctrl(commonf) {
      // define this first so that $timeout is defined when activate is executed
      var $timeout = commonf.$timeout;
    
      activate(); 
    
      function activate() {
        $timeout(function () {
          alert("test");
        }, 5);
    }
    

    In javascript, it is generally good practice to have variable declaration as the first statement in your function.