In regular angularjs ui-router state the controller runs each time the state is activated. I found this not to be the case when dealing with named views in an ionic application. The named view controller runs only once per element(game). Eg. user displays a game -> controller runs. Then user goes to another state and upon their return to displaying the same game controller does not run again - the view uses an already generated scope from before. I would like reinitialise that games scope with controller.
My code:
//app.js
.state('app.game', {
url: "/x/{gameID:int}",
views: {
'menuContent': {
templateUrl: "templates/html/my-game.html",
controller: 'GameCtrl'
}
}
})
...
//controllers.js
controllers.controller('GameCtrl', function ($scope, $stateParams, Game) {
//alert("running controller");
Game.get({id: $stateParams.gameID}, function(res){
$scope.game = res;
});
})
Edit: I actually use this code to go to the view of game (currently playing with guid idea from Steven Wexler)
<ion-view view-title="Games">
<ion-content>
<h1>Games</h1>
<ion-list>
<ion-item nav-clear menu-close href="#/app/x/{{game.id}}?guid= {{guid()}}" ng-repeat="game in games">
{{game.id}}
</ion-item>
</ion-list>
</ion-content>
</ion-view>
I Think your problem is already solved in this post Angular / Ionic - controller only runs once
brandyshea says that you need to add the code you want to run in the $ionicView.enter
event
controller : function( $scope, $cordovaSQLite ){
$scope.$on('$ionicView.enter', function() {
// code to run each time view is entered
});
...
});
You probably are navigating to a state with the same url and params that was previously loaded. One way to force a reload is to pass in a guid as a parameter with your state and set reloadOnSearch=true
(it's true by default). The second way to force a reload is to use the reload option added in version 0.2.5.
Option 1
.state('app.game', {
url: "/x/{gameID:int}/{guid}",
views: {
'menuContent': {
templateUrl: "templates/html/my-game.html",
controller: 'GameCtrl'
}
}
})
$state.go("app.game", { gameId: id, guid: guid });
function guid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
Option 2 (if you have version >= 0.2.5)
.state('app.game', {
url: "/x/{gameID:int}",
views: {
'menuContent': {
templateUrl: "templates/html/my-game.html",
controller: 'GameCtrl'
}
},
reload: true
})
Note: Awesome guid function copied from Create GUID / UUID in JavaScript?