是否可以让一个 Controller 使用另一个 Controller ?
例如:
此 HTML 文档仅打印 MessageCtrl
Controller 在 messageCtrl.js
文件中传递的消息。
<html xmlns:ng="http://angularjs.org/">
<head>
<meta charset="utf-8" />
<title>Inter Controller Communication</title>
</head>
<body>
<div ng:controller="MessageCtrl">
<p>{{message}}</p>
</div>
<!-- Angular Scripts -->
<script src="http://code.angularjs.org/angular-0.9.19.js" ng:autobind></script>
<script src="js/messageCtrl.js" type="text/javascript"></script>
</body>
</html>
Controller 文件包含以下代码:
function MessageCtrl()
{
this.message = function() {
return "The current date is: " + new Date().toString();
};
}
仅打印当前日期;
如果我要添加另一个 Controller ,DateCtrl
,它将特定格式的日期交还给 MessageCtrl
,该怎么做呢? DI 框架似乎与 XmlHttpRequests
和访问服务有关。
Controller 之间有多种通信方式。
最好的可能是共享服务:
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);
}
在这两种情况下,您也可以使用任何指令进行通信。
我是一名优秀的程序员,十分优秀!