Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS reinitialize controller

I have got a controller named newGroupCtrl whose definition is like :

.state('new_group', {
    url: '/new_group',
    templateUrl: 'templates/new_group.html',
    controller: 'newGroupCtrl'
})

.controller('newGroupCtrl', function ($scope, $rootScope,$ionicHistory,$window) {
    $rootScope.roomId = $scope.getRoom();

    $scope.getRoom = function () {
        var date = new Date;
        var minutes = date.getMinutes();
        var hour = date.getHours();
        return 'room_' + hour + '' + minutes;
    };
}

I reach this contoller from previous page by :

$window.location.href = ('#/new_group');

That's good until now. $rootScope.roomId variable is initialized in the newGroupCtrl controller properly.

From this new_group page, I navigate to another page. And when I navigate back to this page by calling $window.location.href = ('#/new_group');, $rootScope.roomId is not initialized again, instead its old value is still there. The state of the newGroupCtrl is preserved.

How can I completely reinitialize newGroupCtrl?

like image 377
Ozgen Avatar asked May 13 '15 08:05

Ozgen


1 Answers

You need to tell state that reload controller each time when URL is getting accessed via browser by just adding adding reload option of state to true like reload: true.

Code

.state('new_group', {
    url: '/new_group',
    templateUrl: 'templates/new_group.html',
    controller: 'newGroupCtrl',
    reload: true //will reload controller when state is being access
});

You should use $state.go('new_group') instead of doing $window.location.href = ('#/new_group'); which will ensure that the route changes will recognize by ui-router.

Same SO answer here

like image 53
Pankaj Parkar Avatar answered Nov 15 '22 04:11

Pankaj Parkar