首页 > 解决方案 > 为什么使用 ng-include 时 pushState 会中断?

问题描述

使用ng-include时,pushState功能中断。

下面是一个简单的例子。

<div ng-app="angularApp" ng-controller="angularCtrl">
    <div ng-include="templateUrl"></div>
    <button ng-click="bye()">BYE</button>
</div>

let app = angular.module('angularApp', []);
app.controller('angularCtrl', async function ($scope) {
    $scope.templateUrl = '/assets/hi.html';
    $scope.bye = function () {
        $scope.templateUrl = '/assets/bye.html';
        history.pushState({},'','/finish.html')
    };
});

我们希望在按下BYE按钮后更改正文值,ng-include并通过 更改页面地址pushState。这个例子是一个更大的项目的一部分,这里已经尽可能地简化了。

注意:根据评论,url 由 pushState 更改,但立即返回其值。它在 ng-include 过程中被忽略。

标签: angularjspushstateangularjs-ng-include

解决方案


在 AngularJS 中更改浏览器位置本身就很棘手。最好尽可能多地使用该$location服务,因为它可以更好地理解和使用$scope摘要机器。

尝试在您的应用中使用以下内容:

let app = angular.module('angularApp', []);
app.config(function ($locationProvider) {
  $locationProvider.html5Mode(true);
});

app.controller('angularCtrl', function ($scope, $timeout, $location) {
    $scope.templateUrl = '/assets/hi.html';
    $scope.bye = function () {
        $scope.templateUrl = '/assets/bye.html';
        $location.url('/finish.html');
    };
});

请注意,您需要base[href]为 html5 模式提供支持:

<html lang="en">
<head>
  ...
  <base href="/">
</head>
<body>
  <div ng-app="angularApp" ng-controller="angularCtrl">
    <div ng-include="templateUrl"></div>
    <button ng-click="bye()">BYE</button>
  </div>
</body>
</html>

推荐阅读