控制器之间使用工厂和承诺共享数据

时间:2016-04-07 04:02:52

标签: angularjs promise factory shared-data

好的,那里有很多关于使用工厂/服务在控制器之间共享数据的问题,但我没有找到适用于我的问题的内容。要么我不正确地解释答案,要么这是一个我要问的有效问题!希望是后者。

我希望控制器2能够识别何时进行了新的http调用并且更新了工厂图像对象。此刻它解析一次,然后忽略任何后续更新。我在俯瞰什么?

我的观点:

<div>
    <ul class="dynamic-grid" angular-grid="pics" grid-width="150" gutter-size="0" angular-grid-id="gallery" refresh-on-img-load="false" >
        <li data-ng-repeat="pic in pics" class="grid" data-ng-clock>
            <img src="{{pic.image.low_res.url}}" class="grid-img" data-actual-width = "{{pic.image.low_res.width}}"  data-actual-height="{{pic.image.low_res.height}}" />
        </li>
    </ul>
</div>

工厂:

.factory('imageService',['$q','$http',function($q,$http){

  var images = {}
  var imageServices = {};
  imageServices.homeImages = function(){
    console.log('fire home images')
      images = $http({
        method: 'GET', 
        url: '/api/insta/geo',
        params: homeLoc
      })
  };
  imageServices.locImages = function(placename){
    console.log('fire locImages')
      images = $http({
        method: 'GET', 
        url: '/api/geo/loc',
        params: placename
      })
  };
  imageServices.getImages = function(){
    console.log('fire get images', images)
    return images;  
  }
  return imageServices;
}]);

控制器1:

angular.module('trailApp.intro', [])

.controller('introCtrl', function($scope, $location, $state, showTrails, imageService) {
  // run the images service so the background can load
  imageService.homeImages();

  var intro = this;

  intro.showlist = false;
  intro.data = [];

  //to get all the trails based on user's selected city and state (collected in the location object that's passed in)
  intro.getList = function(location) {

      intro.city = capitalize(location.city);
      intro.state = capitalize(location.state);
      //get placename for bg

      var placename = {placename: intro.city + ',' + intro.state};
      imageService.locImages(placename);
... do other stuff...

控制器2:

angular.module('trailApp.bkgd', [])
.controller('bkgdCtrl', ['$scope','imageService', 'angularGridInstance', function ($scope,imageService, angularGridInstance) {
  $scope.pics = {};
    imageService.getImages().then(function(data){
      $scope.pics = data;
      console.log($scope.pics);
    });
}]);

1 个答案:

答案 0 :(得分:0)

你的controller2实现只获得了一次图像,你可能需要一个$watch来保持更新:

angular.module('trailApp.bkgd', [])
.controller('bkgdCtrl', ['$scope','imageService', 'angularGridInstance', function ($scope,imageService, angularGridInstance) {
  $scope.pics = {};

  $scope.$watch(function(){
    return imageService.getImages(); // This returns a promise
  }, function(images, oldImages){
    if(images !== oldImages){ // According to your implementation, your images promise changes reference
      images.then(function(data){
        $scope.pics = data;
        console.log($scope.pics);
      });
    }
  });

}]);