Search code examples
javascriptangularjsangularjs-service

Controller cannot access Angular Service variable


I have a problem with my Angular Service. I have two controllers and one service. Basically the first controller gets data via AJAX call and store that data on the service. The second controller then access that data via service. I have successfully passed the data from the 1st controller to the service however, when I access the data from the 2nd controller it returns nothing.

I have one view with 2 controllers by the way.

Thanks

Service

app.service('SharedDataService', function () {
  // Holds subtask that will be passed to other controllers
  // if SharedDataService is invoke.
  var _subTask = {};
  return {
    subTask : _subTask
  };
});

Controller 1

app.controller('MainCategoryController',function($scope,$http,SharedDataService){

    $scope.loadSubtask = function(m_uid){
        $http({
            method: 'POST',
            url: $locationProvider + 'query_stasks',
            data: {
                m_uid: m_uid
            }
        }).then(function successCallback(response) {
                SharedDataService.subTask = response.data;
            },function errorCallback(response){
        });

    }

}

Controller 2

app.controller('SubTaskController',function($scope,$http,$location,$rootScope,SharedDataService){



    $scope.$watch('SharedDataService.subTask', function(newValue,oldValue){
        console.log("ni sud');");
        if (newValue !== oldValue) {
            $scope.subTasks = newValue;
        }   
        return SharedDataService.subTask; 
    });

}


Solution

  • Because SharedDataService is not on $scope, the first argument of the $watch method needs to be a watchExpression function instead of an Angular expression string.

    app.controller('SubTaskController',function($scope,$http,$location,$rootScope,SharedDataService){
    
        $scope.$watch(
            function watchExpression() {return SharedDataService.subTask},
            function listener (newValue,oldValue){
                console.log("ni sud");
                if (newValue !== oldValue) {
                    $scope.subTasks = newValue;
                }
            }    
        });
    
    });
    

    For more information, see AngularJS $rootScope.scope API Reference - $watch.