Reinitialize an Angular.js controller

别来无恙 提交于 2019-11-27 17:23:09

问题


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.


回答1:


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.




回答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);
        }
    }
});


来源:https://stackoverflow.com/questions/17413760/reinitialize-an-angular-js-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!