使用promises在控制器之间共享数据?

时间:2014-02-18 13:43:42

标签: angularjs

好的,我在服务中有这个功能:

wikiServices = angular.module('wikiServices', []);

wikiServices.factory('newsService', function($http, $q){
 var chosenNewsStory = "";

 var getNewsStory = function(news_id, callback){
    var deferred = $q.defer();
    $http({
        method: "GET",
        url: "news/article/" + news_id
    })
    .success(function(newsStory){
        deferred.resolve(newsStory);
        console.log("RESOLVED " + newsStory);   
    });
    return deferred.promise;
 });

控制器1:

wikiControllers =  angular.module('wikiControllers', []);
wikiControllers.controller('ctrl1', ['$scope', 'newsService',
  function($scope, newsService){
   $scope.getNewsStory = newsService.getNewsStory(function(input){
     newsService.getNewsStory(news_id);
   };
});

控制器2:

wikiControllers =  angular.module('wikiControllers', []);
wikiControllers.controller('ctrl1', ['$scope', 'newsService',
  $scope.watch('newsService.chosenNewsStory', function(newVal){
     console.log(newVal);
  });
});

现在,我尝试过设置" selectedNewsStory"在服务中很多地方买了我觉得我错过了整个JS的关键部分 - "体验"。

我在设置" var chosenNewsStory"在从服务器获取的newsStory的服务中。我怎么能这样做?

感谢。

1 个答案:

答案 0 :(得分:1)

您应该为正在共享的变量定义getset方法,并返回这些方法。我会像你这样格式化你的服务:

wikiServices.factory('newsService', function($http, $q){
    var chosenNewsStory = "";

    return {
        getNewsStory: function(news_id, callback){
            var deferred = $q.defer();
            $http({
                method: "GET",
                url: "news/article/" + news_id
            }).success(function(newsStory){
                deferred.resolve(newsStory);
                console.log("RESOLVED " + newsStory);   
            });
            return deferred.promise;
        },

        getNews: function() {
            return chosenNewsStory;
        },

        setNews: function(story) {
            chosenNewsStory = story;
        }
    }
});

现在,您将能够观看newsService.getNews()并使用newsService.setNews(news)

进行设置