簡體   English   中英

AngularJS:通過服務和restangular在控制器之間共享數據

[英]AngularJS : Share data between controllers with service and restangular

我是新手,我仍然在服務方面掙扎,我有一個應用程序可以查詢服務器以進行調查,並在向導中顯示調查問題,調查中的每個問題都在一個路徑中(/ survey /: surveyId / question /:questionId)

我要嘗試的是第一次加載調查,然后使用該加載的數據而無需再次查詢它。

據我了解我需要一項服務,我正在使用Restangular,但我不知道該服務返回什么,這就是我所擁有的:

angular.module('surveys')
    .factory('questionsService', ['Restangular', function (Restangular) {
        var surveyId = 1;

        return {
            questions: Restangular.one("survey", surveyId).getList("questions")
        }
}

然后在我的控制器中,我只是做:

questionsService.questions.then(function (questions) {
            $scope.questions = questions;
            $scope.currentQuestion = $routeParams.page ? $scope.questions[$scope.currentQuestionIndex] : null;
        });

而且這是有效的,我不知道這是否是正確的方法。

但是現在我需要在服務中進行其他操作,例如獲取未回答的問題,這就是我迷路的地方,因為如果我在服務的getUnansweredQuestions()中放置一個函數,我將不知道如何獲取問題,我不知道他們是否已經解決。

我不知道我是否足夠清楚,但是我需要一些建議。

嘗試這樣的事情:

surveys.run(function($rootScope,$http,$q) {
    function getData () {
        var deferred = $q.defer();
        $http(insertConfigObjectHere)
        .success(function (data, status, headers, config) {
            deferred.resolve(data);
        })
        .error (function (data, status, headers, config) {
            deferred.reject();
        });
        return deferred.promise;
    }
    $rootScope.myData = getData();
}

警告:我也是AngularJS的新手,但我認為這可能有效,也未經測試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM