8

The controller can not access the angular service variable

 3 years ago
source link: https://www.codesd.com/item/the-controller-can-not-access-the-angular-service-variable.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

The controller can not access the angular service variable

advertisements

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


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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK