我正在使用服务从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
};
});
Run Code Online (Sandbox Code Playgroud)
我在多个控制器中使用这些数据.
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);
}
Run Code Online (Sandbox Code Playgroud)
我想更新每个控制器中的数据,但是当我更改ControllerA中的$ scope.message时,它不会触发ControllerB中的更改.
编辑:问题是我想避免使用"$ broadcast"和"$ on".
有任何想法吗?
这是一个jsfiddle:http://jsfiddle.net/Victa/McLQD/