0

I'm using angularjs and I am trying to parse a value from a service to my $scope controller. The problem is that is loading first the $scope and then the service. As a result me my scope is always undefinied. I tried many solutions that I found by no-one is worked for me. Can anyone help me please? My service:

'use strict';
angular.module('myApp')
    .service('getCategoriesService', function ($rootScope) {

        getCategories = function () {
            var categoriesByLocation = 1;      
            return categoriesByLocation;
        };

and my controller:

angular.module("myApp")
  .controller('MyCtrl', function ($scope,getCategoriesService) {
         $scope.resultCategory = getCategoriesService.getCategories();
         });

2 Answers 2

1

Use the this. when declaring a function in a service.

.service('getCategoriesService', function ($rootScope) {

        this.getCategories = function () {
            var categoriesByLocation = 1;      
            return categoriesByLocation;
        };

  })

demo

var app = angular.module("myApp",[]);
app.controller('MyCtrl', function ($scope,getCategoriesService) {
         $scope.resultCategory = getCategoriesService.getCategories();
 });
 app.service('getCategoriesService', function ($rootScope) {
    
        this.getCategories = function () {
            var categoriesByLocation = 1;      
            return categoriesByLocation;
        };
        
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  {{resultCategory}}
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer, I have always the same problem, the $scope is loading before the service.
It's definitely the answer. I agree with you
0

Change it as

angular.module("myApp")
  .controller('MyCtrl', function ($scope,getCategoriesService) {
        getCategoriesService.getCategories().then((function (d) {
         $scope.resultCategory = d; 
     }
 });

1 Comment

Thank you for your answer, I have always the same problem, the $scope is loading before the service.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.