【问题标题】:Angular Routing & the ng-viewAngular 路由和 ng-view
【发布时间】:2013-04-08 23:51:23
【问题描述】:

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: '/'
        });
    }]);

【问题讨论】:

  • templateUrl 通常包含 .html 文件的路径。是否缺少扩展程序?

标签: javascript asp.net-mvc angularjs ngroute


【解决方案1】:

根据您的路由配置,我相信您的示例网址缺少井号 (#),因此应该如下所示:

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

#号后面的部分是AngularJS打算解析的路径(即你定义的路由配置)

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

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

在您提到的第二种情况下,AngularJS 不请求index.html,因为它在第一次加载时就被缓存了,并且使用了缓存的副本。

【讨论】:

    【解决方案2】:

    您的 locationProvider 是否针对 HTML5 进行了配置?

    $locationProvider.html5Mode(true);
    

    Using HTML5 pushstate on angular.js

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-05
      • 2016-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多