如何在AngularJS中访问服务内的对象属性?

时间:2014-09-30 11:40:14

标签: angularjs angularjs-directive angularjs-scope angularjs-service angularjs-controller

我有一个带有事件名称的本地变量对象的服务:

    myApp.service('appService', ['$rootScope', function ($rootScope) {

        var events = {
            firstEvent: "MyFirstEvent",
            secondEvent: "MySecondEvent"
        };

        this.doEvent = function(eventName)
       {           
            // do something...
       };


    }]);

现在我正在尝试阅读控制器中的 events.firstEvent

myApp.controller('myController', ['$scope', 'appervice', function ($scope, appService) {

var mydata = appService.events.firstEvent;

}]);

我在控制台中遇到此错误的问题:

TypeError: Cannot read property 'firstEvent' of undefined

我做错了什么?

P.S。 我也无法访问函数doEvent()。

3 个答案:

答案 0 :(得分:1)

你服务返回这个,但你没有放任何东西!

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

这将返回一个包含事件的对象!

答案 1 :(得分:0)

Angular在加载服务时执行服务功能,需要从此函数返回所需的服务。

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;

}]);

答案 2 :(得分:0)

你可以写

function MyService($rootScope){
     var _this = {};

     _this.events = { 
         firstEvent: 'blabla1',
         secondEvent: 'blabla2'
     };
     return _this;
}

myApp.service('appService', ['$rootScope', MyService]);

之后

myApp.controller('myController', ['$scope', 'appService', function ($scope, appService) {

    var mydata = appService.events.firstEvent;

}]);