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

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

问题描述

是否有可能有一个控制器使用其他的?

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>

控制器文件包含以下code:

The controller file contains the following code:

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

它只是显示当前日期;

Which simply prints the current date;

如果我是添加其他控制器, DateCtrl 它交给特定格式的日期回 MessageCtrl ,如何总会有去这样做?该DI框架似乎与 XmlHtt prequests 和访问服务有关。

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.

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

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