1

I have a service with a local variable object with events names:

 myApp.service('appService', ['$rootScope', function ($rootScope) { var events = { firstEvent: "MyFirstEvent", secondEvent: "MySecondEvent" }; this.doEvent = function(eventName) { // do something... }; }]); 

Now I am trying to read events.firstEvent inside a controller:

myApp.controller('myController', ['$scope', 'appervice', function ($scope, appService) { var mydata = appService.events.firstEvent; }]); 

The problem I get this error in console:

TypeError: Cannot read property 'firstEvent' of undefined 

What I'm doing wrong?

P.S. I also can not access the function doEvent().

    3 Answers 3

    1

    You service returns this, but you didn't put anything in there!

    myApp.service('appService', ['$rootScope', function ($rootScope) { var events = { firstEvent: "MyFirstEvent", secondEvent: "MySecondEvent" }; return { events:events}; }]); 

    this will return an obeject with the events in it!

    3
    • What If I'm adding function inside that service. look the edited question. How I can access that function?
      – Aviv M
      CommentedSep 30, 2014 at 11:59
    • got it I think: return { events:events, doEvent: this.doEvent};
      – Aviv M
      CommentedSep 30, 2014 at 12:05
    • 10x a lot for the help.
      – Aviv M
      CommentedSep 30, 2014 at 16:38
    0

    Angular executes services function when loading it, you need to return that you need from this function.

    myApp.service('appService', ['$rootScope', function ($rootScope) { var events = { firstEvent: "MyFirstEvent", secondEvent: "MySecondEvent" }; return events; }]); myApp.controller('myController', ['$scope', 'appervice', function ($scope, appService) { var mydata = appService.firstEvent; }]); 
      0

      You can write

      function MyService($rootScope){ var _this = {}; _this.events = { firstEvent: 'blabla1', secondEvent: 'blabla2' }; return _this; } myApp.service('appService', ['$rootScope', MyService]); 

      and after that

      myApp.controller('myController', ['$scope', 'appService', function ($scope, appService) { var mydata = appService.events.firstEvent; }]); 

        Start asking to get answers

        Find the answer to your question by asking.

        Ask question

        Explore related questions

        See similar questions with these tags.