Angular:更新服务并在控制器之间共享数据
Angular: Update service and share data between controllers
我正在使用一个服务从API获取一些数据:
angular.module('myApp', [])
.factory('myService', function($q, $timeout) {
var getMessages = function() {
var deferred = $q.defer();
$timeout(function() {
deferred.resolve('Hello world!');
}, 2000);
return deferred.promise;
};
return {
getMessages: getMessages
};
});
我在多个控制器中使用这些数据。
function ControllerA($scope, myService) {
$scope.message = myService.getMessages();
$scope.updateMessage = function(){
$scope.message = 'Hello Max';
};
}
function ControllerB($scope, myService) {
$scope.message = myService.getMessages();
$scope.$watch('message', function(){
// 'Hello Max'
}, true);
}
我想更新每个控制器中的数据,但当我更改ControllerA中的$scope.message时,它不会触发ControllerB中的更改。
编辑:问题是我希望避免使用"$broadcast"answers"$on"。
有什么想法吗?
这是一个jsfiddle:http://jsfiddle.net/Victa/McLQD/
您可以使用$broadcast
向rootScope
广播事件,并使用$on
定义侦听器来侦听此特定事件。
function ControllerA($scope, myService, $rootScope) {
$scope.message = myService.getMessages();
$scope.updateMessage = function () {
$scope.message = 'Hello Max';
$rootScope.$broadcast("HelloEvent", {
msg: $scope.message
});
};
}
function ControllerB($scope, myService, $rootScope) {
$scope.message = myService.getMessages();
$rootScope.$on("HelloEvent", function (event, message) {
$scope.message = message.msg;
});
}
更新:
就在你更新问题之前,我得到了上述解决方案。如果你不想使用$broadcast或$on,你可以像这个一样通过$rootScop
e共享对象
function ControllerA($scope, myService, $rootScope) {
$scope.message = myService.getMessages();
$scope.updateMessage = function () {
$scope.message = 'Hello Max';
$rootScope.message = 'Hello Max';
};
}
function ControllerB($scope, myService, $timeout, $rootScope) {
$scope.message = myService.getMessages();
$rootScope.$watch('message', function (oldV, newV) {
if(oldV === undefined && oldV === newV) return;
$scope.message = $rootScope.message;
});
}
使用广播的演示不使用广播的演示
相关文章:
- 获取@ResponseBody的一部分作为主干和Spring MVC控制器之间的参数
- 在控制器之间切换,可以't更新视图
- 使用服务(AngularJS)在控制器之间共享数据
- 通过共享服务在两个不同ng应用程序中的控制器之间共享数据
- 在控制器之间传递变量的最佳方式
- 使用Angularjs在两个不同页面的控制器之间共享数据
- 在Angular Bootstrap Modal和父控制器之间共享作用域
- 2ng控制器,并且需要在控制器之间共享数据
- 如何将json文件中的数据提取到对象数组中,并在两个控制器之间共享
- 如何在多个控制器之间封装设置$scope值
- 在angularJS中使用模态窗口时,在控制器之间共享对象数组
- 在角度上不同控制器之间共享状态
- AngularJS:如何在控制器之间传递变量
- 在OnsenUI+AngularJS+PhoneGap中的控制器之间传递数据
- 使用 AngularJS 在控制器之间传递变量
- 工厂和控制器之间的“绑定”
- Angular,设置一个回调函数,用于在工厂和控制器之间更新
- 如何在控制器之间共享来自休息服务的数据
- AngularJS控制器之间共享代码/方法/功能
- 通过服务在控制器之间同步数据