DaveC426913 DaveC426913 - 1 year ago 77
AngularJS Question

writing a simple Angular Service

OK, I've built services before but obviously I don't actually know what makes them tick, since I can't seem to debug this ultra-simple service call:


var gridApp = angular.module('gridApp', []);
gridApp.controller('mainController', ['$scope', '$http', 'dataService',
function($scope, dataService) {

$scope.message = 'I am Angular and I am working.';

var init = function(){




(function() {
'use strict';

.service('dataService', dataService)

dataService.$inject = [];

function dataService() {

console.log("I am the dataService and I am loaded");

var foo = 1;

function getData () {
return 2;


I see this on-screen: I am Angular and I am working. so Angular is loading.

I see this in console: I am the dataService and I am loaded so the dataService is actually being loaded.

But then the console.log is:

undefined (line 8)

TypeError: dataService.getData is not a function (line 9)

What am I missing?

Answer Source

The previous answers are correct in that your $http injection was wrong, but you are also not attaching your service functions to the service:

function dataService() {
  var dataService = this;  //get a reference to the service

  //attach your functions and variables to the service reference
  dataService.foo = 1;
  dataService.getData = function() {
    return 2;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download