gpt4 book ai didi

javascript - 一个 AngularJS Controller 可以调用另一个吗?

转载 作者:bug小助手 更新时间:2023-10-28 10:53:34 25 4
gpt4 key购买 nike

是否可以让一个 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);
}

在这两种情况下,您也可以使用任何指令进行通信。

关于javascript - 一个 AngularJS Controller 可以调用另一个吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9293423/

25 4 0
文章推荐: javascript - 在 HTML 文件中包含另一个 HTML 文件
文章推荐: html - HTML5 中是否有 minlength 验证属性?
文章推荐: html - 我们可以在同一个 中有多个 吗?