Search code examples
javascriptangularjsparent-childcontrollers

Clear data on logout with injected controllers (Angular)


I have a parent controller with two injected child controllers as follows:

.controller('parentCtrl', ['$scope', '$http', '$controller', '$uibModal', 
     function ($scope, $http, $controller, $uibModal) {

    $controller('firstChildCtrl', { $scope: $scope })
    $controller('secondChildCtrl', { $scope: $scope })

}])

When the user logs out, the login controller emits a logout event:

$scope.$emit('logout');

All my other controllers clear their data on receiving this event, as follows:

 $scope.initial = [];

    $rootScope.$on("logout", function (event) {
        $scope.activities = angular.copy($scope.initial);
    });

So my question is, how can I get the parent controller to clear the data in its child scopes (because it isn't doing that)?

Thanks in advance!


Solution

  • What I did in the end was have a controller where the factories (services to fetch data) were external to the controller, and I injected multiple services into my controller.

    .controller('multiCtrl', ['$scope', '$rootScope', '$http', '$uibModal', '$q', 'getApples', 'getPears', 
            function ($scope, $rootScope, $http, $uibModal, $q, getApples, getPears) {
    
    var myApples = getMyApples.fetch(function (apples) {
          $scope.apples = apples;
    
          var theApples = $scope.apples;
    
          });
    
    var myPears = getMyPears.fetch(function (pears) {
          $scope.pears = pears;
    
          var thePears = $scope.pears;
    
          });
    });