Ozgen Ozgen - 10 months ago 147
AngularJS Question

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.
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');
is not initialized again, instead its old value is still there. The state of the newGroupCtrl is preserved.

How can I completely reinitialize newGroupCtrl?


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.


.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