2

I am communicating from page2 controller to page1 controller in different views using $.emit and $on

     app.controller('mainController', ['$scope', function($scope) {
      $scope.message = "hello main page";
      $scope.$on('frompage2', function(event, data) {
        console.log("in parentController.........." + data);
      })
    }]);

    app.controller('page1Controller', ['$scope', '$rootScope', function($scope, $rootScope) {
      $scope.message = "hello page1";
      var msgFromPage2 = $rootScope.$on('frompage2', function(event, data) {
        console.log("in page1 controller" + data);

      })

      $scope.$on('$destroy', function() {
        msgFromPage2()
      });

    }]);

    app.controller('page2Controller', ['$scope',
      function($scope) {

        $scope.message = "Hello page 2"
        $scope.$emit('frompage2', 'this is from page2');

      }
    ]);

Its working fine if I don't use page1 controller scope destroy method to unsubscribe from event listening. What should be the correct approach to handle this situation so that I can subscribe to page2controller messages and still using destroy method in page1 controller scope to unsubscribe whenever page1 is getting unloaded

1]: http://plnkr.co/edit/dgitQBPRDjn9Z98kQ8Ad?p=preview

Amit
  • 338
  • 1
  • 2
  • 9

1 Answers1

0

You cannot communicate between these particular controllers because they are on different views and when one of them is initialized the second is not. Whenever you switch the view the controller responsible for that view is reinitialized and the other is destroyed.

To enable them to share some data you can use a service. Here is a good example how you can do that.

S.Klechkovski
  • 4,005
  • 16
  • 27
  • Thanks !!. I am just wondering can I use angularjs broadcat/emit and on method to complete that workflow.. I can still listen to page2 messages in page1 using $rootscope.on but issue is that if I unsubscribe from it from page 1 scope destroy method communication is not happening which is correct behavior. What should be better approach if I use angularjs broadcast/emit mechanism – Amit Sep 21 '15 at 07:14