在AngularJS中,控制器和指令之间的通信可以通过以下几种方式解决:
// 控制器
app.controller('MyCtrl', function($scope, $rootScope) {
$scope.sendMessage = function() {
$rootScope.$broadcast('messageEvent', 'Hello from controller!');
};
});
// 指令
app.directive('myDirective', function() {
return {
restrict: 'E',
link: function(scope) {
scope.$on('messageEvent', function(event, message) {
console.log(message); // 输出:Hello from controller!
});
}
};
});
// 控制器
app.controller('MyCtrl', function($scope) {
$scope.message = 'Hello from controller!';
});
// 指令
app.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
message: '='
},
template: '{{ message }}
',
};
});
// 服务
app.service('MessageService', function() {
var message = '';
this.setMessage = function(newMessage) {
message = newMessage;
};
this.getMessage = function() {
return message;
};
});
// 控制器
app.controller('MyCtrl', function($scope, MessageService) {
$scope.sendMessage = function() {
MessageService.setMessage('Hello from controller!');
};
});
// 指令
app.directive('myDirective', function(MessageService) {
return {
restrict: 'E',
link: function(scope) {
scope.message = MessageService.getMessage();
},
template: '{{ message }}
',
};
});
这些方法可以根据实际需求选择使用,根据具体情况选择最适合的方式来实现控制器和指令之间的通信。