问题描述
如果您有一个控制器来操作 Angular.js 中的 $scope 变量,是否有一种惯用的方法:
if you have a controller to manipulate $scope variables in Angular.js, is there an idiomatic way to:
- 重置控制器的 $scope 和
- 重启控制器初始化?
对于复杂的控制器,不必将每个变量重置为其初始值会非常方便,特别是如果您真正想要的是控制器和范围的简单重新初始化.但是,通过 $location.path()
再次导航到相同的 URL 没有帮助.
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.
假设我不能使用任何 $window.location
hack,因为这会违反 Chrome Packaged Apps 中的 CSP.
Suppose I can't use any $window.location
hack because this would violate the CSP in Chrome Packaged Apps.
推荐答案
刚问完,我终于找到了一种使用 $route.reload()
.
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.
这篇关于重新初始化 Angular.js 控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!