How to use $emit and $on of angularjs for two diff

2019-09-14 08: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;
 });