I'm attempting to use UI-router to manage state change in my app. I thought that changing states on a dynamic route would cause the current scope to be destroyed and a new scope created for the template being re-inserted with the new content, for example:
$stateProvider
.state('foo', {
url: '/:id'
views: {
'foo@': {
templateUrl: 'partials/foo.html',
controller: 'Foo',
controllerAs: 'FooCtrl as foo'
}
}
});
I thought the state above would destroy & create the FooCtrl each time the user navigated to a route with a different id. Thus, running the initialization functions located in FooCtrl on each route change to initialize the current view with the right data from the services being injected into the controller. I've been listening in my controllers for the $scope.$destroy
function to be run on these state changes, but they aren't called.
What I'm curious about is, what is the idiomatic way to create & destroy controllers to get the functionality I described above? Also, is there a more idiomatic way to achieve the same thing in AngularJS?
Thanks!
UPDATE:
In order to destroy and re-create the controller when using $state.go()
you must pass the {reload: true}
option as the 3rd parameter as below.
$state.go('foo', {id: '1'}, {reload: true})
As Radim stated, there should be no need to call {reload: true}
in order for the controller to be re-instantiated. Currently, I'm listening for $stateChangeStart
to make sure that the state is actually being updated. After seeing that it is, I'm listening for $scope.$on('$destroy')
and it is not firing. So for some reason, state is being changed without the controller being destroyed & re-instantiated.
UPDATE WORKING The error I was making was that in my deepest nested views I was using an absolute path. This seemed to persist the controller from state to state. When I made the nested views relative they are being destroyed and re-created on state change as Radim described.