【问题标题】:How can I make $routeProvider to work properly in angularjs如何使 $routeProvider 在 angularjs 中正常工作
【发布时间】:2015-02-05 17:43:57
【问题描述】:

我正在尝试手动构建一个 shell 试图弄清楚它是如何工作的

结构:

- application(php stuff)

- webroot
-- app
--- app.js

-- templates
--- main
---- login
----- login.html

index.html (with angularjs libs)

app.js:

function config($routeProvider){
    $routeProvider
        .when("/login",{
            templateUrl: "../templates/main/login/login.html"
        })
        .otherwise({ redirectTo:"/other" });
}


angular
    .module("app", ["ngRoute", "ngResource"])
    .config(config);

登录:

<div>LOGIN test template</div>

"/other" 不退出。 此外,我尝试了不同的路径: 模板网址:“模板/main/login/login.html” templateUrl: "webroot/templates/main/login/login.html"

顺便说一下,url 带有一个“#”(例如 nameDomain.com/#/login,但它应该是 nameDomain.com/#login)但 angularjs 似乎只允许 /nameUrlTemplate

【问题讨论】:

    标签: javascript angularjs configuration angularjs-ng-route


    【解决方案1】:

    查看 Angular 的 routeProvider 文档,因为这应该可以消除您的一些困惑。

    我认为您在这里想要做的是在您的.otherwise 中使用现有路由,因为由于/other 没有在任何地方定义,Angular 不会知道您用它做什么:

    var app = angular.module('app', ['ngRoute', 'ngResource']);
    app.config(function config($routeProvider) {
      $routeProvider
        .when('/', {
          templateUrl: '../templates/main/index.html'
        })
        .when('/login', {
          templateUrl: '../templates/main/login/login.html'
        })
        .otherwise({
          redirectTo: '/'
        });
    });
    

    我相信这应该会给您想要的效果。显然,您可以根据需要对其进行调整,例如,如果您想为未定义的任何内容设置 404 路由/模板。就目前而言,这将始终回退到不存在的特定路线的主页。当您考虑用户和登录/退出状态时,这会变得更加复杂,但这更像是一个概念验证。

    此外,ngRoute 将默认以/#/foo 的格式呈现 URL,因为它使用 hashbang 样式的格式,这使得搜索引擎的爬虫能够解析和读取各种页面/状态一个 JavaScript webpp。您指的是文档片段,爬虫不可索引。您可以在 Google 的Webmaster docs 上阅读更多关于差异的信息。

    【讨论】:

    • 我的 WHEN 有什么问题 .when('/login',{ templateUrl: '../templates/main/login/login.html' })
    • 另外:我想要 /#login 而不是 /#/login
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    相关资源
    最近更新 更多