一个 AngularJS 控制器是否可以调用另一个控制器?
一个 AngularJS 控制器是否可以调用另一个控制器?
是否有可能让一个控制器使用另一个控制器?
例如:
这个HTML文档仅仅输出messageCtrl.js
文件里的MessageCtrl
控制器传递过来的信息。
{{message}}
控制器文件包含以下代码:
function MessageCtrl() { this.message = function() { return "The current date is: " + new Date().toString(); }; }
它仅仅输出当前日期;
如果我增加另一个控制器DateCtrl
并且以一种特定的格式将日期传回给MessageCtrl
,怎么做?DI框架似乎与XmlHttpRequests
和访问服务有关。
admin 更改状态以发布 2023年5月23日
查看这个fiddle:http://jsfiddle.net/simpulton/XqDxG/
同时观看以下视频:控制器之间的通信
Html:
javascript:
var myModule = angular.module('myModule', []); myModule.factory('mySharedService', function($rootScope) { var sharedService = {}; sharedService.message = ''; sharedService.prepForBroadcast = function(msg) { this.message = msg; this.broadcastItem(); }; sharedService.broadcastItem = function() { $rootScope.$broadcast('handleBroadcast'); }; return sharedService; }); function ControllerZero($scope, sharedService) { $scope.handleClick = function(msg) { sharedService.prepForBroadcast(msg); }; $scope.$on('handleBroadcast', function() { $scope.message = sharedService.message; }); } function ControllerOne($scope, sharedService) { $scope.$on('handleBroadcast', function() { $scope.message = 'ONE: ' + sharedService.message; }); } function ControllerTwo($scope, sharedService) { $scope.$on('handleBroadcast', function() { $scope.message = 'TWO: ' + sharedService.message; }); } ControllerZero.$inject = ['$scope', 'mySharedService']; ControllerOne.$inject = ['$scope', 'mySharedService']; ControllerTwo.$inject = ['$scope', 'mySharedService'];
有多种方式可以在控制器之间进行通信。
最好的一种方法可能是共享一个服务:
function FirstController(someDataService) { // use the data service, bind to template... // or call methods on someDataService to send a request to server } function SecondController(someDataService) { // has a reference to the same instance of the service // so if the service updates state for example, this controller knows about it }
另一种方式是在作用域上发出事件:
function FirstController($scope) { $scope.$on('someEvent', function(event, args) {}); // another controller or even directive } function SecondController($scope) { $scope.$emit('someEvent', args); }
在这两种情况下,您也可以与任何指令进行通信。