1

Was wondering what is the best way to refresh controller scope on route change?

Any help would be appreciated!

3
  • Do you mean when the URL changes but the page and controller stays the same? Commented Oct 16, 2014 at 1:58
  • Yep. lets say when I'm navigating from /old_path to /new_path, I want to reset data on OldPathController. Commented Oct 16, 2014 at 1:59
  • Are you using built in router or ui router? Commented Oct 16, 2014 at 2:15

1 Answer 1

4

I would refactor to have all my initialisation of data properties on the scope in a single function, called something like initScope() that is called when the controller is first run, and also on the $routeChangeSuccess (and probably also $routeChangeUpdate if you want to handle changes to the URL that resolve to the same route) event(s).

e.g.

app.controller('MyCtrl', ['$scope', function ($scope) {
    function initScope() {
        $scope.foo = 1;
        $scope.bar = { ram: 'ewe' };
    }

    initScope();

    $scope.$on('$routeChangeUpdate', initScope);
    $scope.$on('$routeChangeSuccess', initScope);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.