我搜索了很多关于这一点,虽然我发现了一些类似的问题,但它们并不是我想要的。
想象一下这种代码:
angular
.module('foobar', ['ngResource'])
.service('Brand', ['$resource', function($resource){
return $resource('/api/v1/brands/:id', { id: '@id' });
}])
.service('Product', ['$resource', function($resource){
return $resource('/api/v1/products/:id', { id: '@id' });
}])
.controller('ProductController', ['$scope', 'Brand', function($scope, Brand){
$scope.brands = Brand.query();
}])
.controller('BrandController', ['$scope', 'Brand', function($scope, Brand){
this.create = function() {
Brand.save({label: $scope.label });
};
}])
目前,我正在使用$broadcast
和$on
在品牌控制器中
Brand.save({label: $scope.label }, function(brand){
$rootScope.$broadcast('brand-created', brand);
});
在产品控制器中
$scope.$on('brand-created', function(brand){
$scope.brands.push(brand);
});
它有效,但我不喜欢这种同步数据的方式。
想象一下,你有10个必须同步的控制器,你应该在每个控制器中写$scope.$on
部分。并为每项服务保存...
是否有更好的方法可以在任何地方使用收藏同步?
答案 0 :(得分:0)
是 - 使用共享服务。我在我的例子中使用了http,但你可以很容易地用$ resource替换它。这里的要点是保留品牌列表的内存副本。此副本由productscontroller引用,无论何时更新,它都会自动反映。您只需确保在进行$ http put / resource put调用后正确更新它。
http://plnkr.co/edit/k6rwS0?p=preview
angular.module('foobar', [])
.service('Brand', ['$http', '$q',
function($http, $q) {
var brandsList;
return {
getBrands: function() {
var deferred = $q.defer();
//if we have not fetched any brands yet, then we'll get them from the api
if (!brandsList) {
$http.get('brands.json').then(function(response) {
brandsList = response.data;
console.log('brands:' + brandsList);
deferred.resolve(brandsList);
});
} else {
deferred.resolve(brandsList);
}
return deferred.promise;
},
save: function(newBrand) {
// $http.put('brands.json', newBrand).then(function(){
// //update the list here on success
// brandsList.push(newBrand)
// })
brandsList.push({
name: newBrand
});
}
};
}])
.controller('productsController', ['$scope', 'Brand',
function($scope, Brand) {
Brand.getBrands().then(function(brands) {
$scope.brands = brands;
})
}
])
.controller('brandsController', ['$scope', 'Brand',
function($scope, Brand) {
$scope.create = function() {
Brand.save($scope.label);
};
}
])