2014-02-18 95 views
1

好吧,我有一個服務這一功能:使用承諾在控制器之間共享數據?

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

現在,我已經在嘗試設置 「chosenNewsStory」服務很多地方buyt我認爲我錯過了整個JS-「體驗」的關鍵部分。

我在從服務器獲取的newsStory服務中設置「var chosenNewsStory」時遇到了問題。我怎樣才能做到這一點?

謝謝。

+0

設置請出示更多的代碼 –

+0

會做,當我回家。 – mr2k

+0

好的,它已更新。 :) – mr2k

回答

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)

+0

所以我應該在調用getNewsStory的控制器中使用setNews? – mr2k

+0

是的,這將設置它在服務和你的其他控制'$ watch'(現在應該看'newsService.getNews()')應該改變。 – tymeJV

相關問題