我有以下代码,使页面能够在URL变量中跟踪页面上的状态:
模板:
<div>id = {{id}}</div>
<div>uid = {{uid}}</div>
<div>score = {{score}}</div>
<button ng-click="changeNumber()">change</button>
控制器:
mainApp.controller('pagestateController', function ($scope, $log, $location) {
urlVariables = $location.search();
$scope.id = urlVariables.id === undefined ? 0 : urlVariables.id;
$scope.uid = urlVariables.uid === undefined ? 0 : urlVariables.uid;
$scope.score = urlVariables.score === undefined ? 0 : urlVariables.score;
$scope.changeNumber = function() {
$scope.urlManagerChangeVariable('id', Math.floor(Math.random() * 60) + 20);
$scope.urlManagerChangeVariable('uid', Math.floor(Math.random() * 60) + 20);
$scope.urlManagerChangeVariable('score', Math.floor(Math.random() * 60) + 20);
};
$scope.urlManagerChangeVariable = function(name, value) {
urlVariables = $location.search();
urlVariables[name] = value;
$location.search(urlVariables);
$scope.id = urlVariables.id;
$scope.uid = urlVariables.uid;
$scope.score = urlVariables.score;
}
});
每次单击按钮时都可以正常工作,三个URL变量会发生变化,因此如果用户创建书签或复制URL,则返回页面时,可以重建所有状态。
但是,至少在Firefox中,如果我:
Ctrl
- 书签或Shift
- 书签可以使用,但会打开一个新窗口/标签,或者在我转到新书签后,我可以重新加载页面,页面上的数字将会然后反映URL变量。
当用户从一个书签切换到另一个书签时,有没有办法强制Angular重新执行控制器?
我正在使用ui-router并添加了以下.config
部分,但没有有效的
mainApp.controller('pagestateController', function ($scope, $log, $location) {
//$state.forceReload(); //produces endless loop
//$state.reload(); //produces endless loop
//$state.go($state.current, {}, {reload: true}); //produces endless loop
urlVariables = $location.search();
$scope.id = urlVariables.id === undefined ? 0 : urlVariables.id;
$scope.uid = urlVariables.uid === undefined ? 0 : urlVariables.uid;
$scope.score = urlVariables.score === undefined ? 0 : urlVariables.score;
$scope.changeNumber = function() {
$scope.urlManagerChangeVariable('id', Math.floor(Math.random() * 60) + 20);
$scope.urlManagerChangeVariable('uid', Math.floor(Math.random() * 60) + 20);
$scope.urlManagerChangeVariable('score', Math.floor(Math.random() * 60) + 20);
};
$scope.urlManagerChangeVariable = function(name, value) {
urlVariables = $location.search();
urlVariables[name] = value;
$location.search(urlVariables);
$scope.id = urlVariables.id;
$scope.uid = urlVariables.uid;
$scope.score = urlVariables.score;
}
}).config(function($provide) {
$provide.decorator('$state', function($delegate, $stateParams) {
$delegate.forceReload = function() {
return $delegate.go($delegate.current, $stateParams, {
reload: true,
inherit: false,
notify: true
});
};
return $delegate;
});
});