Angular:在控制器之间共享异步服务数据
Angular: share asynchronous service data between controllers
我想在控制器之间"绑定更改"异步数据。
我知道这可能有点令人困惑,但我希望有可能。
在下面的例子中,如果我在输入中写一些东西,效果会很好:http://jsfiddle.net/Victa/9NRS9/
HTML:
<div ng-app="myApp">
<div ng-controller="ControllerA">
ControllerA.message = {{message.hello}}<br/>
<input type="text" ng-model="message.hello"/>
</div>
<hr/>
<div ng-controller="ControllerB">
ControllerB.message = {{message.hello}}<br/>
<input type="text" ng-model="message.hello"/>
</div>
</div>
JS:
angular.module('myApp', [])
.factory('myService', function($q, $timeout) {
var message = {
hello: 'hello world'
};
return {
getMessage : function(){
return message;
}
};
})
function ControllerA($scope, myService) {
$scope.message = myService.getMessage();
}
function ControllerB($scope, myService) {
$scope.message = myService.getMessage();
}
但假设我从服务器上获取数据。我想像前面的例子一样"链接"数据。http://jsfiddle.net/Victa/j3KJj/
问题是,我希望避免使用"$broadcast"/"$on"或在$rootScope中共享对象。
HTML:
<div ng-app="myApp">
<div ng-controller="ControllerA">
ControllerA.message = {{message.hello}}<br/>
<input type="text" ng-model="message.hello"/>
</div>
<hr/>
<div ng-controller="ControllerB">
ControllerB.message = {{message.hello}}<br/>
<input type="text" ng-model="message.hello"/>
</div>
</div>
JS:
angular.module('myApp', [])
.factory('myService', function($q, $timeout) {
var message = {};
return {
getMessage : function(){
var deferred = $q.defer();
$timeout(function() {
message.hello = 'Hello world!';
deferred.resolve(message);
}, 2000);
return deferred.promise;
}
};
})
function ControllerA($scope, myService) {
$scope.message = myService.getMessage();
}
function ControllerB($scope, myService) {
$scope.message = myService.getMessage();
}
谢谢你的帮助。
Victor
在factory
的返回对象中返回promise
,而不是实际对象本身。因此,在您的范围内,您实际上应该等待修复具体对象的承诺,然后将其分配给$scope.message
示例:
function ControllerA($scope, myService) {
myService.getMessage().then(function(obj){
$scope.message=obj
});
}
我把你的小提琴换成了可能是你答案的东西,看看这个小提琴
相关文章:
- 当视图在AngularJS中返回时,我如何获得异步服务调用来更新视图
- 如何在Angular中设置异步HTTP服务的回调,以便在不定义数组的情况下在控制器中填充数组
- 如何访问回调函数之外的异步angularjs服务数据
- 异步http请求服务
- 在异步内部函数返回 [UI-路由器和 HTML 服务] 之后返回外部 fn
- 如何将指令模型绑定到异步服务数据
- 如何从 angularjs 服务中的异步调用返回响应
- 将 Javascript .js(调用 Web 服务)异步加载到页面中
- AngularJS函数在多次异步服务调用后
- 异步服务调用不工作
- 如何在调用异步Web服务响应时将值设置为数组
- Angular:在控制器之间共享异步服务数据
- 将一个服务(工厂)注入到另一个服务中,这两个服务都是异步的
- Angular.js将数据从异步服务传递到作用域
- 用TypeScript编写的Geocoder谷歌地图服务的因果报应异步测试
- 如何在服务中使用异步库
- 如何在javascript中实现异步服务调用
- 异步服务调用后,nhandsontable数据流未定义
- 如何将异步服务中的数据设置到控制器$scope中?
- 避免在Angular.js中重复异步服务初始化