20

if you have a controller to manipulate $scope variables in Angular.js, is there an idiomatic way to:

  • reset the controller's $scope, and
  • restart controller initialization?

For complex controllers it would be very convenient not to have to reset every variable to it's initial value, especially if what you really want is a simple reinitialization of the controller and the scope. Navigating to the same URL again via $location.path() doesn't help, though.

Edit: Suppose I can't use any $window.location hack because this would violate the CSP in Chrome Packaged Apps.

2 Answers 2

24

Just after asking, I finally found one way to solve this using $route.reload().

myapp.Controller('SampleController', function($location, $route) {

  $scope.navTo = function(url) {
    if ($location.path() === url) {
      $route.reload();
    } else {
      $location.path(url);
    }
  }

});

I'm still thinking, that there must be some more elegant solution, but this definitely works for me.

Sign up to request clarification or add additional context in comments.

3 Comments

I don't agree, I think this is a perfectly elegant solution. In a sense, you're reloading the page, so $route.reload() makes a lot of sense.
@popovitsj: While it's great to know that this doesn't have to be considered bad practice, I'm still not really convinced. While you're definitely right that there's some appeal to this solution because semantically $route.reload() is similiar to reloading the page, it still produces a lot of overhead. This might be ignorable in a lot of specific use cases (it definitly was in mine at that time), but it would still be nice to have an equally clean method that avoids creating this overhead.
Can we move the contents of oninit in a private method (say it 'init') and call it from oninit and finally use the same private method to reset the controller as many times as we want?
2

If you are using angular-ui-router then you should do it in this way:

myapp.Controller('SampleController', function($state) {

    $scope.navigate = function (stateName) {
        if ($state.is(stateName)) {
            $state.reload();
        } else {
            $state.go(stateName);
        }
    }
});

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.