简体   繁体   English

在浏览器中更改URL参数时刷新角度页面

[英]Angular page refresh on changing URL parameter in browser

Extremely simple requirement but having a hard time with this. 极其简单的要求,但是很难。 Have simple page where I print the parameter in the url path. 有一个简单的页面,我在其中在url路径中打印参数。

http://localhost:8888/ngtest.html#/1234567

ngtest.html ngtest.html

<div ng-app="app" ng-controller="testCtrl">
    {{myId}}
</div>

<script>
var app = angular.module('app', []);
app.controller('testCtrl', function($scope, $location) {
    $scope.myId = $location.$$path;
});
</script>

In the browser window: 在浏览器窗口中:

  1. change 1234567 to something like 1234 1234567更改为1234
  2. hit Enter 点击Enter

Nothing happens. 什么都没发生。 Hit F5 and it works as expected. 按F5,它按预期工作。

Not sure if this has something to do with browser behavior but how to force the page to refresh after parameter change + Enter? 不知道这是否与浏览器行为有关,但是如何在参数更改+ Enter之后强制页面刷新?

Page refresh has been answered here. 页面刷新已在此处回答

You can use $route.reload(); 您可以使用$route.reload();

As suggested here, you can try listening for route change success when hitting Enter in the url input: 如此处的建议当在url输入中按Enter时您可以尝试侦听路由更改成功:

scope.$on('$routeChangeSuccess') or scope.$on('$locationChangeSuccess'). scope.$on('$routeChangeSuccess')scope.$on('$locationChangeSuccess').

Complete example based on Leon's suggestion above 基于上述莱昂建议的完整示例

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js"></script>

<div ng-app="app" ng-controller="testCtrl">
    {{myId}}
</div>

<script>
var app = angular.module('app', []);
app.controller('testCtrl', function($scope, $location) {

    // add a listener for when the url changes and user
    // Enter in the address bar
    $scope.$on('$locationChangeStart', function(event) {
        $scope.myId = $location.$$path;
    }); 
});
</script>

Basically location this is registering a location change listener and doing things accordingly. 基本上,这是注册一个位置更改侦听器并相应地执行操作。 No routing config required 无需路由配置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM