Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reinitialize an Angular.js controller

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.

like image 253
bfncs Avatar asked Jul 01 '13 21:07

bfncs


2 Answers

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.

like image 146
bfncs Avatar answered Oct 22 '22 20:10

bfncs


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);
        }
    }
});
like image 22
Ali Gonabadi Avatar answered Oct 22 '22 18:10

Ali Gonabadi