【问题标题】:Angular page refresh on changing URL parameter in browser在浏览器中更改 URL 参数时的 Angular 页面刷新
【发布时间】:2015-07-30 11:35:54
【问题描述】:

非常简单的要求,但很难做到。有一个简单的页面,我在 url 路径中打印参数。

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

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>

在浏览器窗口中:

  1. 1234567 更改为1234
  2. 回车

什么都没有发生。按 F5 即可按预期工作。

不确定这是否与浏览器行为有关,但如何在参数更改+回车后强制页面刷新?

【问题讨论】:

  • 您可能需要为此设置路由功能。见:youtube.com/…
  • 为什么还要刷新? SPA 的重点是避免这种情况。
  • 如果有效,不刷新肯定没问题。基本上我有像http://example.com/view.html#/{item_number} 这样的入站链接。试图看看它是否可以在没有路由的情况下工作。

标签: javascript angularjs browser


【解决方案1】:

根据上面 Leon 的建议完成示例

<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>

基本上定位是注册一个位置改变监听器并做相应的事情。无需路由配置

【讨论】:

    【解决方案2】:

    页面刷新已回复here.

    你可以使用$route.reload();

    正如here, 建议的那样,您可以在输入 url 时尝试监听路由更改是否成功:

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

    【讨论】:

    • 在下面找到注册添加的完整代码。不需要重新加载路由。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-22
    • 2018-03-09
    • 2020-08-26
    • 1970-01-01
    相关资源
    最近更新 更多