我要寻找与AngularJS最佳做法: 我需要共享嵌套的控制器之间的JSON Ajax响应。 Controller1-> Controller2-> Controller3
现在我有一个工作版本,简单地设置一个$ scope.variable在控制器1的反应,而其他控制器通过调用相同的变量访问。
我试图创建一个全球性的服务,但问题是我做的一个控制器Ajax调用,并在Ajax调用完成之前,全局变量默认为null所有其他控制器。
我只是想了解什么最好的办法是在这种情况下。
感谢
解决方案创建发布/订阅服务或工厂和订阅从控制器2和3对数据变化的方法。就像这样:
角
.module('')
.factory('GlobalAjaxVariable',函数(){
变种订户= [];
发布功能(数据){
callbacks.forEach(函数(CLB){
CLB(数据);
});
}
返回 {
使用setData:功能(ajaxData){
发布(ajaxData);
},
addSubscriber:功能(CLB){
subscribers.push(CLB);
}
};
});
I am looking for best practices with AngularJS: I need to share a json ajax response between nested controllers. Controller1->Controller2->Controller3
Right now I have a working version that simply sets a $scope.variable with the response in controller1, and the other controllers access it by calling the same variable.
I have tried creating a global service, but the problem is I make the ajax call in a controller, and before the ajax call is finished, the global variable defaults to null for all the other controllers.
I am just trying to understand what best approach is in this situation.
Thanks
解决方案Create publisher/subscriber service or factory and subscribe methods from your controller2 and 3 to data change. Just like this:
angular
.module('')
.factory('GlobalAjaxVariable', function() {
var subscribers = [];
function publish(data) {
callbacks.forEach(function(clb) {
clb(data);
});
}
return {
setData: function(ajaxData) {
publish(ajaxData);
},
addSubscriber: function(clb) {
subscribers.push(clb);
}
};
});