gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 10:53:23 26 4
gpt4 key购买 nike

我正在尝试手动构建一个 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 样式的格式,可以为搜索引擎提供爬虫程序能够解析和读取 JavaScript webpp 的各种页面/状态。您所指的是文档片段,爬虫无法对其进行索引。您可以在 Google 的 Webmaster docs 上阅读有关差异的更多信息。 .

关于javascript - 如何使 $routeProvider 在 angularjs 中正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28350619/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com