加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 一个控制器可以调用另一个?

发布时间:2020-12-17 09:23:05 所属栏目:安全 来源:网络整理
导读:有可能有一个控制器使用另一个? 例如: 这个HTML文档只是在MessageCtrl.js文件中打印由MessageCtrl控制器发送的消息。 html xmlns:ng="http://angularjs.org/"head meta charset="utf-8" / titleInter Controller Communication/title/headbody div ng:cont
有可能有一个控制器使用另一个?

例如:

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

<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和访问服务。

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

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读