Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - detect when a controller is `unloaded`

I'm new be in angular. I want to know before viewDashboard controller will unload and I'm not sure how I can detect that.

Basicali after click an item from left menu Template.fn_change_view() changing Template.active_view to active view name e.g. 'dashboard' and it show/hide some view- element directives.

But after that code written inside inactive directive controller not execute any more. Before that happen I need to execute one function from this inactive controller. Is there any way to do that?

I hope I write that clear enough, if not I will try to explain better.

HTML:

index.html

 <body class="template" ng-controller="TemplateController as Template" ng-class="{'on': Template.loged_in}">
    <div class="mainFlexCont">            
        <left-menu class="menuFlexCont menu" ng-class="{'open': Menu.isMenuOpen}"></left-menu>
        <!-- dashboard is visible only when  Template.active_view is equal to 'dashboard' -->            
        <view-dashboard class="contentFlexCont" ng-if="Template.fn_active_view('dashboard')"></view-dashboard>            
        <!-- ... -->
    </div>    
    <!-- ... -->
</body>                                

left-menu.html loaded by leftMenu directive

<ul class="leftMenu">
    <li>
        <a class="toggleLeft" ng-click="Menu.isMenuOpen = !Menu.isMenuOpen" href>
            <i class="fa fa-bars"></i> Toggle Menu
        </a>
    </li>   
    <!-- view change by clicking one of list items -->
    <li ng-repeat="item in Menu.obj_items" ng-click="Template.fn_change_view(item.active)" ng-class="{'active' : Template.fn_active_view(item.active)}">
        <a href>
            <i class="fa {{item.icon}}"></i> {{item.label}}
        </a>
    </li>
 </ul>

dashboard.html - loaded by viewDashboard directive

<div class="row">
    <div class="col-xs-12">
        <h1>Dashboard</h1>
    </div>
</div>
<div class="row">
    <div class="col-lg-7">
        <chart-yearly class="chart"></chart-yearly>
    </div>
</div>

JS:

chartYearly directive

app.directive('chartYearly', function () {
    return{
        restrict: 'E',
        templateUrl: 'views/chart-yearly.html',
        controller: function ($scope) {
            // how I can detect here before Yearly controler will be unloaded?
            // when Template.active_view will change to different than dashboard
                $scope.$watch('Template.active_view', function () {
                    // I need to execute this when this directive is active either before is unloaded 
                    console.log(2);
                });
        },
        controllerAs: 'Yearly'
    };
like image 661
LJ Wadowski Avatar asked Dec 28 '14 10:12

LJ Wadowski


1 Answers

Scopes emit a $destroy event. See events section in the angular docs.

$scope.$on('$destroy', function() {
  // clean up stuff
})
like image 119
AJcodez Avatar answered Oct 19 '22 21:10

AJcodez