Currently, I am working on implementing UI-router to handle state changes in my application. My initial belief was that switching states on a dynamic route would result in the current scope getting destroyed and a new scope being created for the template with updated content. For example:
$stateProvider
.state('foo', {
url: '/:id'
views: {
'foo@': {
templateUrl: 'partials/foo.html',
controller: 'Foo',
controllerAs: 'FooCtrl as foo'
}
}
});
I had assumed that the state above would recreate the FooCtrl every time a user navigated to a different id route. This would trigger the initialization functions within FooCtrl to load the correct data from the injected services each time the route changed. I have been monitoring for $scope.$destroy
function in my controllers during these state changes, but they do not seem to be triggered.
I am wondering what is the recommended way to create and destroy controllers to achieve the functionality I just described? Furthermore, is there a more standardized approach to accomplish the same outcome in AngularJS?
Thank you!
UPDATE:
To ensure the destruction and recreation of the controller when using $state.go()
, it is necessary to include the {reload: true}
option as the third parameter like so:
$state.go('foo', {id: '1'}, {reload: true})
Based on Radim's explanation, calling {reload: true}
should not be required for the controller to be reinstantiated. Currently, I am checking for $stateChangeStart
to confirm the state update. Once verified, I am waiting for $scope.$on('$destroy')
event to fire, yet it does not. It seems that the state is changing without properly destroying and recreating the controller.
UPDATE WORKING I discovered that the issue was caused by using an absolute path in my deepest nested views. This was preventing the controller from being recreated between states. Switching to relative paths resolved this problem, allowing the controllers to be properly destroyed and recreated as mentioned by Radim.