小编典典

一个AngularJS控制器可以调用另一个吗?

html

一个控制器可以使用另一个控制器吗?

例如:

该HTML文档仅MessageCtrlmessageCtrl.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>

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

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

它只是打印当前日期;

如果我要添加另一个控制器,DateCtrl它将特定格式的日期返回给MessageCtrl,那么该怎么做呢?DI框架似乎与XmlHttpRequests服务有关。


阅读 486

收藏
2020-05-10

共1个答案

小编典典

控制器之间有多种通信方式。

最好的一种可能是共享服务:

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);
}

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

2020-05-10