<!--test.htm-->
<html ng-app="app">
<body>
<div ng-controller="ControllerOne">
<span>ControllerOne</span> <input ng-model="message" >
<button ng-click="handleClick(message);">BROADCAST</button>
</div>
<div ng-controller="ControllerTwo">
<span>ControllerTwo</span>
<input ng-model="message" >
</div>
<div >
<span>my-component</span>
<my-component ng-model="message"></my-component>
</div>
</body>
<script>
var app = angular.module('app', []);
app.factory('sharedService', function($rootScope) {
var sharedService = {};
sharedService.message = '';
sharedService.prepForBroadcast = function(msg) {
this.message = msg;
this.broadcastItem();
};
sharedService.broadcastItem = function() {
$rootScope.$broadcast('myEvent');
};
return sharedService;
});
app.controller('ControllerOne', ['$scope', 'sharedService',ControllerOne]);
app.controller('ControllerTwo', ['$scope', 'sharedService',ControllerTwo]);
function ControllerOne($scope, sharedService) {
$scope.handleClick = function(msg) {
sharedService.prepForBroadcast(msg);
};
$scope.$on('myEvent', function() {
$scope.message = 'ONE: ' + sharedService.message;
});
}
function ControllerTwo($scope, sharedService) {
$scope.$on('myEvent', function() {
$scope.message = 'TWO: ' + sharedService.message;
});
}
app.directive('myComponent', function(sharedService) {
return {
restrict: 'E',
controller: function($scope, $attrs, sharedService) {
$scope.$on('myEvent', function() {
$scope.message = 'Directive: ' + sharedService.message
});
},
replace: true,
template: '<input>'
};
});
</script>
</html>
本文探讨了Angular应用中如何通过广播机制实现Controller和组件间的通信,包括使用服务共享状态和监听事件来传递消息的过程。
254

被折叠的 条评论
为什么被折叠?



