How to use $emit and $on of angularjs for two different controller stored in different path

你说的曾经没有我的故事 提交于 2019-12-12 00:49:26

问题


I have two views and its resp controller. Say view1.html and its controller firstCntrl and view2.html and its controller secndCntrl.

In view1.html:

There is Link2 which will be redirected to view2.html if it is clicked.

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

in ng-click I am calling emit function where I defined $emit as firstCntrl.js

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

I want to send true from here and catch it in $on.

In view2.html

There are two div. say div one and div two.

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

What I want that If user clicks on first link then it should show the first div of view2.html

Or

if user clicks on second link then it should show sencod div of view2.html View two have his own Secnd controller. I am struck here. Help me in this How to do this. Thanking you in anticipation.


回答1:


I think you don't need emit here since firstCtrl and secondCtrl is a separated controller. In case there is no parent-child relation between your scopes you can inject $rootScope into the controller and broadcast the event to all child scopes.

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

Use $scope.on instead of $rootScope.on to prevent memory leak issue.

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


来源:https://stackoverflow.com/questions/41647183/how-to-use-emit-and-on-of-angularjs-for-two-different-controller-stored-in-dif

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!