一个AngularJS控制器可以调用另一个吗? [英] Can one AngularJS controller call another?

查看:93
本文介绍了一个AngularJS控制器可以调用另一个吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以让一个控制器使用另一个?

Is it possible to have one controller use another?

例如:

这个HTML文档只是在 messageCtrl.js 文件中打印由 MessageCtrl 控制器发送的消息。

This HTML document simply prints a message delivered by the MessageCtrl controller in the messageCtrl.js file.

<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>

控制器文件包含以下代码:

The controller file contains the following code:

function MessageCtrl()
{
    this.message = function() { 
        return "The current date is: " + new Date().toString(); 
    };
}

只打印当前日期;

如果我要添加另一个控制器, DateCtrl 将特定格式的日期交回 MessageCtrl ,怎么会这样做呢? DI框架似乎关注 XmlHttpRequests 并访问服务。

If I were to add another controller, DateCtrl which handed the date in a specific format back to MessageCtrl, how would one go about doing this? The DI framework seems to be concerned with XmlHttpRequests and accessing services.

推荐答案

如何在控制器之间进行通信有多种方法。

There are multiple ways how to communicate between controllers.

最好的方法可能是共享服务:

The best one is probably sharing a service:

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
}

另一种方式是发出范围上的事件:

Another way is emitting an event on scope:

function FirstController($scope) 
{
  $scope.$on('someEvent', function(event, args) {});
  // another controller or even directive
}

function SecondController($scope) 
{
  $scope.$emit('someEvent', args);
}

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

In both cases, you can communicate with any directive as well.

这篇关于一个AngularJS控制器可以调用另一个吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆