0

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

我希望控制器 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);
    });
}]);
4

1 回答 1

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

}]);
于 2016-04-07T04:09:25.873 回答