使用$http和多个控制器的AngularJS工厂。

时间:2022-07-01 11:19:17

I want multiple controllers to be able to update a single view attached to one controller using a factory with $http.

我希望多个控制器能够使用$http的工厂更新连接到一个控制器的单个视图。

My list view:

我的列表视图:

<div class="list" ng-repeat="image in images" ng-controller="controller1">
   <div lass="item"><img src="{{image.url}}" /></div>
</div>

Service:

服务:

.factory("imageService", function($http) {
  return {
    getImages: function() {
      return $http({
        method: "get",
        url: "http://example.com/images",
        params: { user: window.localStorage['user_id'] }
      })
    }
  }
});

Controller 1:

控制器1:

.controller('controller1', function($scope, imageService) {
   window.localStorage['user_id'] = '101';
   var handleSuccess = function(data, status) {
       $scope.images = data;
   };
   imageService.getImages().success(handleSuccess);
})

This all works. When the app is loaded, the list immediately is populated with a list of images for user '101'.

这一切工作。当加载该应用程序时,该列表将立即填充用户“101”的图像列表。

In another controller, I want to be able to switch users and automatically re-poupulate the image list in the view from controller 1 with new images.

在另一个控制器中,我希望能够切换用户并使用新的图像自动地将视图中的图像列表从控制器1中重新装入。

Controller 2:

控制器2:

.controller('controller2', function($scope, imageService) {
   window.localStorage['user_id'] = '202';
   imageService.getImages();
})

So controller 2 will run getImages() and I can see the $http request working via chrome dev tools / XHR. And I know why the list view attached to controller1 is not populating, but I dont know how to make it populate. I have tried moving the success callback into the service and setting a 'images' property on the service and a $scope.images in controller1, but no luck there.

因此,控制器2将运行getImages(),我可以看到通过chrome dev工具/ XHR工作的$http请求。我知道为什么对controller1附加的列表视图没有填充,但是我不知道如何使它填充。我尝试将success回调移动到服务中,并在服务和$scope上设置“images”属性。图像在控制器1,但没有运气。

How can I force the new list of images into the view attached to controller 1?

如何将新的图像列表强制到附加到控制器1的视图中?

2 个解决方案

#1


3  

You should just manage a list into your service that you will bind to your controller1 :

您只需将列表管理到您的服务中,并将其绑定到控制器1:

.factory("imageService", function($http) {
    var service = {};
    service.images = {};
    service.images.list = [];
    service.getImages = function(userId) {
      window.localStorage['user_id'] = userId;
      return $http({
        method: "get",
        url: "http://example.com/images",
        params: { user: userId }
      }).success(function(data){
          service.images.list = data
      });
    }

  //at the initialization of the service, you launch the getImages once with the localStorage value.
  service.getImages(window.localStorage['user_id']);

  return service;
});

Then you can bind it like this in your controllers :

然后你可以像这样在控制器中绑定它:

.controller('controller1', function($scope, imageService) {
   $scope.images = imageService.images;
   //then access it in the view with images.list
   imageService.getImages(101);
})

.controller('controller2', function($scope, imageService) {
   $scope.images = imageService.images;
   //then access it in the view with images.list
   imageService.getImages(202);
})

Note that using a sub object (images.list instead of images) is important.

注意使用子对象(图像)。列表而不是图像)很重要。

If you want some more precise informations about why this sub object is needed you can read this answer on this subject

如果您想要关于为什么需要这个子对象的更精确的信息,您可以阅读这个主题的答案

Hope it helped.

希望它帮助。

#2


0  

I think you can just use one controller. At some time point, say, a user clicks some button, reload the image lists and re-render the view to show the list.

我想你可以用一个控制器。在某些时候,例如,用户单击某个按钮,重新加载图像列表并重新呈现视图以显示列表。

For example, make the factory like:

例如,把工厂做成:

.factory("imageService", function($http) {
  return {
    getImages: function(userId) {
      return $http({
        method: "get",
        url: "http://example.com/images",
        params: { user: userId }
      });
    }
  };
});

And in the controller:

和控制器:

.controller('imageController', function($scope, imageService) {

   function refreshImages (userId) {
     imageService.getImages(userId).success(function(data) {
       $scope.$apply(function () {
         $scope.images = data;
       });
     });
   }

   refreshImages('101');
   $scope.loadImages = function (userId) {
     refreshImages(userId);
   };
});

#1


3  

You should just manage a list into your service that you will bind to your controller1 :

您只需将列表管理到您的服务中,并将其绑定到控制器1:

.factory("imageService", function($http) {
    var service = {};
    service.images = {};
    service.images.list = [];
    service.getImages = function(userId) {
      window.localStorage['user_id'] = userId;
      return $http({
        method: "get",
        url: "http://example.com/images",
        params: { user: userId }
      }).success(function(data){
          service.images.list = data
      });
    }

  //at the initialization of the service, you launch the getImages once with the localStorage value.
  service.getImages(window.localStorage['user_id']);

  return service;
});

Then you can bind it like this in your controllers :

然后你可以像这样在控制器中绑定它:

.controller('controller1', function($scope, imageService) {
   $scope.images = imageService.images;
   //then access it in the view with images.list
   imageService.getImages(101);
})

.controller('controller2', function($scope, imageService) {
   $scope.images = imageService.images;
   //then access it in the view with images.list
   imageService.getImages(202);
})

Note that using a sub object (images.list instead of images) is important.

注意使用子对象(图像)。列表而不是图像)很重要。

If you want some more precise informations about why this sub object is needed you can read this answer on this subject

如果您想要关于为什么需要这个子对象的更精确的信息,您可以阅读这个主题的答案

Hope it helped.

希望它帮助。

#2


0  

I think you can just use one controller. At some time point, say, a user clicks some button, reload the image lists and re-render the view to show the list.

我想你可以用一个控制器。在某些时候,例如,用户单击某个按钮,重新加载图像列表并重新呈现视图以显示列表。

For example, make the factory like:

例如,把工厂做成:

.factory("imageService", function($http) {
  return {
    getImages: function(userId) {
      return $http({
        method: "get",
        url: "http://example.com/images",
        params: { user: userId }
      });
    }
  };
});

And in the controller:

和控制器:

.controller('imageController', function($scope, imageService) {

   function refreshImages (userId) {
     imageService.getImages(userId).success(function(data) {
       $scope.$apply(function () {
         $scope.images = data;
       });
     });
   }

   refreshImages('101');
   $scope.loadImages = function (userId) {
     refreshImages(userId);
   };
});