【问题标题】:How to use $emit and $on of angularjs for two different controller stored in different path如何为存储在不同路径中的两个不同控制器使用 angularjs 的 $emit 和 $on
【发布时间】:2017-01-14 05:45:09
【问题描述】:

我有两个视图及其对应的控制器。 说 view1.html 及其控制器 firstCntrl 和 view2.html 及其控制器 secndCntrl。

view1.html中:

有Link2,点击后会跳转到view2.html。

<a href="#/view1" ng-click="emit()">Link1</a>  
<a href="#/view2" ng-click="emit()">Link2</a>

在 ng-click 中,我调用了 emit 函数,其中我将 $emit 定义为 firstCntrl.js

 app.controller("firstCntrl", function ($scope) {
    $scope.emit = function() {
      $scope.$emit('send', { message: 'true' });
    };
 });

我想从这里发送 true 并在 $on 中捕获它。

view2.html

有两个div。说 div 1 和 div 2。

<div ng-show="one">Hello</div>
<div ng-show="two">World</div>

我想要什么如果用户点击第一个链接,那么它应该显示 view2.html 的第一个 div

或者

如果用户点击第二个链接,那么它应该显示 view2.html 的 sencod div 视图二有他自己的Secnd控制器。我在这里感到震惊。 帮助我如何做到这一点。感谢你在期待。

【问题讨论】:

    标签: angularjs angularjs-scope emit


    【解决方案1】:

    我认为你不需要在这里发出,因为 firstCtrl 和 secondCtrl 是一个单独的控制器。如果您的范围之间没有父子关系,您可以将 $rootScope 注入控制器并将事件广播到所有子范围。

    View1.html

    <a href="#/view1" ng-click="broadcastMsg(1)">Link1</a>  
    <a href="#/view2" ng-click="broadcastMsg(2)">Link2</a>
    

    firstCtrl

    app.controller("firstCntrl", function ($scope, $rootScope) {
        $scope.broadcastMsg = function(id) {
          if (id == 1) 
              $rootScope.$broadcast('send', 'One');
          else 
              $rootScope.$broadcast('send', 'Two');
        };
     });
    

    View2.html

    <div ng-show="showOne">Hello</div>
    <div ng-show="!showOne">World</div>
    

    parentCntrl

    使用 $scope.on 而不是 $rootScope.on 来防止内存泄漏问题。

    app.controller("parentCntrl", function ($scope, $rootScope) {
          $scope.$on('send', function (evt, message) {
                if (message == 'One') 
                    $scope.showOne = true;
                else
                    $scope.showOne = false;
          });
     });
    

    secondCtrl

    app.controller("secondCntrl", function ($scope) {
          $scope.showOne = $scope.$parent.showOne;
     });
    

    【讨论】:

    • 我注意到一件事,如果我点击 msg1 或 msg 2 但它只显示 World。没有你好
    • 我面临一个错误,即 $broadcast 在单击时不起作用。我必须点击两次。 @数字
    • 我认为这不是错误。这是执行的延迟。您可以通过将 console.log('enter') 放入 rootscope.on 来调试代码吗?第一次点击会得到什么?
    • 没有。我在第二次点击它后得到它@digit
    • 我已将我的 $broadcast 放在控制器的末尾。所以基本上发生的事情是当 $broadcast 开始时它重定向到控制器的开始。 Ans 在第二次点击它的搜索 $on
    猜你喜欢
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    • 1970-01-01
    相关资源
    最近更新 更多