Varvara Jones Varvara Jones - 7 days ago 7
AngularJS Question

AngularJS Service issue on sharing data with the Controller

I have the following service which successfully connects to a php file for me and grabs data from the database:

(function(){
'use strict';
angular.module('app.services')
.factory('myService', [ 'getContent', function(getContent, $resource, $scope) {


return {
//list of things returned by this service:

getEventTypes: function(dir, file) {
var getAllTypes = getContent.getphp(dir, file);

getAllTypes.query(function(data){

$scope.mytypes = data;

});
}
};

}])
;

})();


But I cannot assign data to any variables through it. In fact, $scope.mytypes gives me a "Cannot set property 'etypes' of undefined"... I am not sure what's going on? If I remove $resource and $scope then it doesn't work as I am injecting another service into this service... Blegh. Suggestions?

Answer

Don't use $scope in the service which is not advisable.

As Angulajs is a MVC framework M-model should be bound between the V-view and the C-controller where $scope here is the model - the entity which connects the view to the controller.

Hence, we should not use this in the service and won't work as expected.

We usually use one controller per view and if we have any generic logics should be reused in multiple controllers like generic validation, API call etc, it should be used in the service. That's why Service is built as a singleton object which means only one instance will be created in the SPA (Single Page Application) and shared across multiple controllers. But unique controller and $scope should be created per view.

Hope you understand this. Hence your above service can be modified as below to return the promise of the API call where you can use the same inside the controller to call and assign the object to the $scope.

Service

return {
                //list of things returned by this service:

                getEventTypes: function(dir, file) {
                    var getAllTypes = getContent.getphp(dir, file);

                    return getAllTypes;
                }
            };

Controller

myService.getEventTypes(/* params */).query(function(data) { $scope.myTypes = data; });
Comments