Javascript 在 angular.js 上使用 HTML5 pushstate

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11095179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:26:00  来源:igfitidea点击:

Using HTML5 pushstate on angular.js

javascriptangularjs

提问by hilarl

I am trying to implement html5's pushstate instead of the # navigation used by Angularjs. I have tried searching google for an answer and also tried the angular irc chat room with no luck yet.

我正在尝试实现 html5 的 pushstate 而不是 Angularjs 使用的 # 导航。我试过在谷歌上搜索答案,也试过 angular irc 聊天室,但没有成功。

This is my controllers.js:

这是我的controllers.js

function PhoneListCtrl($scope, $http) {
    $http.get('phones/phones.json').success(function(data) {
        $scope.phones = data;
    });
}

function PhoneDetailCtrl($scope, $routeParams) {
  $scope.phoneId = $routeParams.phoneId;
}

function greetCntr($scope, $window) {
    $scope.greet = function() {
    $("#modal").slideDown();
    }
}

app.js

应用程序.js

angular.module('phoneapp', []).
    config(['$routeProvider', function($routeProvider){
        $routeProvider.
            when('/phones', {
                templateUrl: 'partials/phone-list.html',
                controller: PhoneListCtrl
            }).
            when('/phones/:phoneId', {
                templateUrl: 'partials/phone-detail.html',
                controller: PhoneDetailCtrl
            }).
            otherwise({
                redirectTo: '/phones'
            });
    }])

回答by Andrew Joslin

Inject $locationProvider into your config, and set $locationProvider.html5Mode(true).

将 $locationProvider 注入您的配置,并设置$locationProvider.html5Mode(true).

http://docs.angularjs.org/api/ng.$locationProvider

http://docs.angularjs.org/api/ng.$locationProvider

Simple example:

简单的例子:

JS:

JS:

myApp.config(function($routeProvider, $locationProvider) {
  $locationProvider.html5Mode(true);
  $routeProvider
    .when('/page1', { template: 'page1.html', controller: 'Page1Ctrl' })
    .when('/page2', { template: 'page2.html', controller: 'Page2Ctrl' })
});

HTML:

HTML:

<a href="/page1">Page 1</a> | <a href="/page2">Page 2</a>