Nesh Nesh - 6 months ago 32
AngularJS Question

Routing issue with ui-router in ionic (AngularJS)

I have UI routes defined in ionic, and made a

console.log
in controller, but my problem is when I switch between URLs using ng-href="/#/LINK" then no data displayed in console, but when I refresh the same page I am able to see the data in console .... let me know what I am doing wrong here.

Routes -

.state('app.roomone', {
url: "/roomone/:id",
views: {
'menuContent': {
templateUrl: "templates/roomone.html",
controller: 'RoomoneCtrl'
}
}
})

.state('app.roomtwo', {
url: "/selecroom/:roomname/:roomindex",
views: {
'menuContent': {
templateUrl: "templates/roomtwo.html",
controller: 'RoomtwoCtrl'
}
}
})


Following are my controllers -

.controller('RoomoneCtrl', function($scope, $rootScope) {
console.log("I am in room one");
});

.controller('RoomtwoCtrl', function($scope, $rootScope) {
console.log("I am in room two");
});


In my template - I am having simple --
<a ng-href="/#/roomone/MY_ID" />Dummy Link</a>


Problem - Only on refresh(F5) I am getting console values like ""I am in room one"" not on simple navigation of link. Let me know what I am doing wrong.

Answer

As pointed out in the comments: the view is cashed and therefore the controller is not initialized the second time you visit the page.

One solution was not mentioned in Template does not update when using ui-router and ion-tabs. (change cashing to false in view or in router) therefor I adding an extra answer here (better was adding it to comments but with the code example this would become unclear)

Listen in your controller (or directive) to the $ionicView.beforeEnter event to know when a view is active.

.controller('RoomoneCtrl', function($scope, $rootScope) {
    $scope.$on('$ionicView.beforeEnter', function () {
        // (on first time added to DOM and after the view becomes active after cached
        // change some value on your scope
        $scope.date = new Date();
        console.log("I am in room one");
    });
});

For ionic view events see: http://ionicframework.com/docs/api/directive/ionView/

Comments