2

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; 
    });

}

0

5 Answers 5

1

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.

0
1

May be you should save the value use object in service.In my project, i always do like this:

app.service('SharedDataService', function () {
  var service = {};
  service._subTask = '';
  service.toogle_sub_task = function(v){
    if(v){
        service._subTask = v;
    }
    return service._subTask;
  }
  return service;
});

Then, in your controller. You should call service.toogle_sub_task to set and get value. Just give it a try.Best wishes.

0

you have to write a method to store the data into service and return the data from service

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

and in controller call

SharedDataService.setSubTask(response.data);

to set the data...

0

try it

    app.service('SharedDataService', function () {
   this._subTask ={};
});

 // keep code same  1st controller
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){
    });

   }

  }

// 2nd controller

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

 console.log(SharedDataService._subTask );
 });
0

The best practice is to make any $http/resource calls in services and not in controller or directives directly. This makes the code more module and less interlinked.

You should ideally have

app.factory('SharedDataService', function ($http) {
         var subtasks = [];
         var saveSubtasks = function(sub){
           subtasks = sub;
           console.log(subtasks)
         }
         var tasks = {
          loadSubtasks : function(m_uid){
            $http({
                      method: 'POST',
                      url: $locationProvider + 'query_stasks',
                      data: {
                          m_uid: m_uid
                      }
                }).then(function(data){
                  saveSubtasks(data);
                });
          },
          getSubtasks : function(){
            return subtasks;
            }
          }
        return tasks;
    });

and use it like

app.controller('SharedDataService',function($scope,SharedDataService){
  $scope.load = function(val){
    SharedDataService.loadSubtasks(val);
  }
});

app.controller('SubTaskController',function($scope,SharedDataService){
  $scope.get = function(){
    $scope.subtasks = SharedDataService.getSubtasks();
    console.log($scope.subtasks);

  }
});

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.