gpt4 book ai didi

javascript - Angular $location.state() 与 history.pushState 行为

转载 作者:搜寻专家 更新时间:2023-11-01 04:43:17 25 4
gpt4 key购买 nike

我正在尝试构建一个概念验证单页应用程序,它使用历史 API 来存储 View 的状态,这样当用户使用浏览器的后退和前进按钮导航时,将显示之前的状态。

这个简单的例子是一系列页面链接和一些显示的值,以显示状态的状态(没有双关语意)。

这一切都在一个功能性的 plnkr

基本 View :

<div ng-app="testApp">
<div ng-controller="testCtrl">
<h1>State Data: {{data.displayText}}</h1>
<h2>Current Page: {{data.currentPage}}</h2>
<a ng-click="goToPage(page)" ng-repeat="page in pages" class="page">{{page}}</a>
</div>
</div>

应用/ Controller :

var testApp = angular.module('testApp', ['ngRoute'])
.config(function($locationProvider) {
$locationProvider.html5Mode(true);
});

testApp.controller('testCtrl', ['$scope', '$location', function ($scope, $location) {

// Hardcode some pages
$scope.pages = [1, 2, 3, 4, 5, 6, 7, 8, 9];

// Set initial data
$scope.data = {
currentPage: 1,
displayText: "This is the initial state"
};

// Set initial data in state
$location.state($scope.data);

// Watch for location changes so we can apply state accordingly
$scope.$on('$locationChangeSuccess', function (a, newUrl, oldUrl) {
$scope.data = $location.state();
});

// Move between pages
$scope.goToPage = function (page) {

$scope.data.currentPage = page;
$scope.data.displayText = "This is page " + page;

$location.search("page", page);
$location.state($scope.data);

//history.pushState($scope.data, null, '/ThisPage?page=' + page);
};
}]);

您会注意到注释的 history.pushState() 行。 使用该行而不是上面的 $location.search() 和 $location.state() 行实际上可以像我一样工作和执行期待,但我希望使用正确的 Angular 方式让它工作。

编辑: 明确地说,我不是在问我是否应该以 Angular 方式执行此操作。我在问什么是正确的 Angular 方法来让这个工作。 $scope.goToPage() 中对 $location 的两次调用不起作用,但对 history.pushState(注释行)的调用有效。对于如何使用纯 Angular 实现这一点,我显然缺少一些东西,而这正是我需要帮助的地方。干杯!

最佳答案

根据官方网站上的 AngularJS 文档,使用 $location.search 和 state 而不是 history 绝对没问题。

https://docs.angularjs.org/api/ng/service/ $位置

如果您使用的是纯 AngularJS,始终建议您使用 Angular 方式

history.pushState 不是 Angular 代码,它只是一种操作浏览器历史记录的方式,查看链接以获取更多详细信息

https://developer.mozilla.org/en-US/docs/Web/API/History_API

所以我总是希望您使用 $location.search 和 $location.state 而不是 history.pushState

关于javascript - Angular $location.state() 与 history.pushState 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34667498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com