如何使$routeProvider在angularjs中正常工作

How can I make $routeProvider to work properly in angularjs

本文关键字:常工作 工作 何使 routeProvider angularjs      更新时间:2023-09-26

我试图手动构建一个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"不会退出。此外,我尝试了不同的途径:templateUrl:"templates/main/login/login.html"templateUrl:"webroot/templates/main/login/login.html"

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

看看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风格的格式,这使得搜索引擎的爬网程序能够解析和读取JavaScriptWebpp的各种页面/状态。您所指的是一个文档片段,它是而不是可由爬网程序索引的。你可以在谷歌的网站管理员文档上阅读更多关于差异的信息。