angularjs - 为什么使用 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 过程中被忽略。
解决方案
在 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>
推荐阅读
- wordpress - 在多站点上从 4.9.7 更新到 5.3.3 后永久链接损坏
- arrays - How to initialize an array of objects when an array of double is already set?
- java - 用于测试创建和异常功能的 Junit 集成测试问题
- java - 通过递归打印数字序列
- c - 解析 HTTP 响应以仅存储文件路径并测试它是否存在
- python - MongoDB 唯一复合索引允许重复
- angularjs - Angular8:如何过滤唯一记录
- typescript - TypeScript 将字符串转换为对象数组
- microsoft-teams - 使用 Graph API 从后台作业创建 MS Teams 会议
- python - 在 android ndk 中找不到 python.h 库