angularjs – Angular ngRoute – 如果手动输入url,则无法获取页面

前端之家收集整理的这篇文章主要介绍了angularjs – Angular ngRoute – 如果手动输入url,则无法获取页面前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是AngularJS的初学者并且有以下问题.我正在玩ngRoute模块,到目前为止这是我的代码

HTML

<nav ng-controller="navController as nav">
    <ul>
        <li ng-repeat="item in navItems">
            <a href="{{ item.url }}">{{ item.name }}</a>
        </li>
    </ul>
</nav>


<div id="main">
    <div ng-view></div>
</div>

app.js

(function(window) {

    var app = angular.module('app',['ngRoute']);

    app.config(['$routeProvider','$locationProvider',function($routeProvider,$locationProvider) {
        $routeProvider
            .when('/',{
                templateUrl : 'pages/home.html',controller  : 'mainController'
            })
            .when('/contact',{
                templateUrl : 'pages/contact.html',controller  : 'contactController'
            });

        if (window.history && window.history.pushState) {
            $locationProvider.html5Mode(true);
        }
    }]);


    app.controller('mainController',['$scope',function($scope) {
        $scope.message = 'Hello from home page';
    }]);


    app.controller('contactController',function($scope) {
        $scope.message = 'Hello from contact page';
    }]);

    app.controller('navController',function($scope) {
        $scope.navItems = [
            { name: 'Home',url: '/' },{ name: 'Contact',url: '/contact' }
        ];
    }]);

})(window);

它工作正常. Angular渲染菜单,当我点击链接时,它会显示我想要的页面.但除以下情况外.当它显示主页(网址:http://localhost:3000)并且我手动添加到网址“/ contact”时,我得到空白页面,错误“无法获取/联系”.有人可以解释一下为什么会发生这种情况,我该如何解决?我将不胜感激任何帮助.谢谢.

解决方法

实际上,对于非HTML5浏览器,您需要#(#标签).

否则,他们只会在提到的href上对服务器进行HTTP调用. #是一个旧的浏览器短路,它不会触发请求,这允许许多js框架在其上构建自己的客户端重新路由.

您可以使用$locationProvider.html5Mode(true)告诉angular使用HTML5策略(如果可用).

这里是支持HTML5策略的浏览器列表:http://caniuse.com/#feat=history

资料来源:AngularJS routing without the hash ‘#’

猜你在找的Angularjs相关文章