Angular Routing & the ng-view

Angular Routing & the ng-view

本文关键字:the ng-view amp Routing Angular      更新时间:2023-09-26

angular怎么知道要向包含'ng-view'元素的模板视图发出请求?

如果我在应用程序中直接导航到

http://localhost/Categories/List/accessories

。因为索引模板中包含了渲染所有视图所需的'ng-view'元素,所以仍然会向'/或索引模板'发出请求。

当我从索引导航到/Categories/List/accessories时,没有再次请求索引。

下面是我的基本路由,部分复制自GitHub上的Angular MVC"CookBook"示例

angular.module('myApp', ['myApp.ctrl.list'])
    .config(['$routeProvider', '$locationProvider', function ($routeProvider) {
        $routeProvider.when('/', {
            templateUrl: '/Home/Splash',
        });
        $routeProvider.when('/Categories/List/:slug', {
            templateUrl: '/Categories/List',
            controller: 'listCtrl',
        });
        $routeProvider.otherwise({
            redirectTo: '/'
        });
    }]);

在你的路由配置中,我相信你的示例url缺少一个井号(#),所以它应该看起来像:

http://localhost/#/Categories/List/accessories

#符号后面的部分是AngularJS打算解析的路径(例如:您定义的路由配置)

当您在浏览器地址栏中输入上述URL时,浏览器会自动在localhost上查找index.html。当URL中只有域名时,大多数浏览器(如果不是全部的话)都设置为查找index.html。

#符号后面的部分呢?你可能会问。根据定义,#符号之后的路径不会被发送到服务器,因此浏览器不太关心该部分是由什么组成的。

在你提到的第二个场景中,AngularJS不请求index.html,因为它在第一次加载时就被缓存了,并且使用了缓存的副本。

您的locationProvider是否配置为HTML5?

$locationProvider.html5Mode(true);

参见Using HTML5 pushstate on angular.js