Controller无法访问Angular Service变量

时间:2016-05-06 08:46:04

标签: javascript angularjs angularjs-service

我的Angular服务有问题。我有两个控制器和一个服务。基本上,第一个控制器通过AJAX调用获取数据并将该数据存储在服务上。然后第二个控制器通过服务访问该数据。我已成功将数据从第一个控制器传递到服务,但是当我从第二个控制器访问数据时,它什么也没有返回。

顺便说一下,我有一个带2个控制器的视图。

由于

服务

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

控制器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){
        });

    }

}

控制器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; 
    });

}

5 个答案:

答案 0 :(得分:1)

可能你应该在服务中保存值使用对象。在我的项目中,我总是这样:

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

然后,在你的控制器中。您应该调用service.toogle_sub_task来设置和获取值。试一试。最好的祝福。

答案 1 :(得分:1)

由于SharedDataService不在$scope上,$watch method的第一个参数必须是watchExpression function,而不是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;
            }
        }    
    });

});

有关详细信息,请参阅AngularJS $rootScope.scope API Reference - $watch

答案 2 :(得分:0)

您必须编写一种方法将数据存储到服务中并从服务中返回数据

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

并在控制器调用中

SharedDataService.setSubTask(response.data);

设置数据......

答案 3 :(得分:0)

试试吧

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

答案 4 :(得分:0)

最佳做法是在服务中进行任何$ http / resource调用,而不是直接在控制器或指令中进行。这使代码更多模块,而不是相互关联。

理想情况下你应该

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

并像

一样使用它
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);

  }
});