Angularjs 使用factory和promises在控制器之间共享数据
好的,关于使用工厂/服务在控制器之间共享数据有很多,但我没有找到适用于我的问题的方法。要么我对答案的解释不正确,要么这是我将要问的一个有效问题!希望是后者 我希望控制器2能够识别何时进行了新的http调用,何时更新了factory images对象。此时,它解析一次,然后忽略任何后续更新。我忽略了什么 我的看法是:Angularjs 使用factory和promises在控制器之间共享数据,angularjs,promise,factory,shared-data,Angularjs,Promise,Factory,Shared Data,好的,关于使用工厂/服务在控制器之间共享数据有很多,但我没有找到适用于我的问题的方法。要么我对答案的解释不正确,要么这是我将要问的一个有效问题!希望是后者 我希望控制器2能够识别何时进行了新的http调用,何时更新了factory images对象。此时,它解析一次,然后忽略任何后续更新。我忽略了什么 我的看法是: <div> <ul class="dynamic-grid" angular-grid="pics" grid-width="150" gutter-siz
<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>
控制员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);
});
}]);
您的controller2实现只获得一次图像,您可能需要更新:
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);
});
}
});
}]);
谢谢,这个解决方案有效。我想我收到了一些相互矛盾的信息,因为我认为$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);
});
}
});
}]);