【问题标题】:routeProvider - second when() not workingrouteProvider - 第二个 when() 不工作
【发布时间】:2015-06-16 02:39:18
【问题描述】:

我正在学习 AngularJS 路由,但似乎无法弄清楚为什么 $routeProvider 上的第二个 when() 不起作用。

index.html

<html lang="en" ng-app="myApp" class="no-js"> 
<head>
    <meta charset="utf-8">
    <title>My AngularJS App</title>
    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css"/>
</head>
<body>
<div>
    <ng-view></ng-view>
</div>
<!-- In production use:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/x.x.x/angular.min.js"></script>
-->
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="app.js"></script>
</body>
</html>

app.js

'use strict';

// Declare app level module which depends on views, and components
var app = angular.module('myApp', [
    'ngRoute'
]);
app.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.
        when('/', {templateUrl: 'partials/li.html', controller: 'MainCtrl'}).
        when('/new', {templateUrl: 'partials/edit.html'}).
        otherwise({redirectTo: "/"})
}]);

app.controller('MainCtrl', ['$scope', 'persons', function ($scope, persons) {
    $scope.persons = persons
}]);


app.factory('persons', [function () {
    var persons = [
        {fname: "Dave", lname: "Thomas"},
        {fname: "John", lname: "Smith"},
        {fname: "Jason", lname: "Doe"},
        {fname: "Stupid", lname: "Guy"},
    ];
    return persons;
}]);

li.html(由于某种原因,我无法在 WebStorm 中将其另存为 list.html)

<table class="table table-striped" style="width: auto" >
    <thead>
    <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <td><a href="/new"><span class="glyphicon glyphicon-plus"></span></a></td>
    </tr>
    </thead>
    <tbody ng-repeat="person in persons">
    <tr >
        <td>{{person.fname}}</td>
        <td>{{person.lname}}</td>
        <td><a href="/edit"><span class="glyphicon glyphicon-edit"></span ></a></td>
    </tr>
    </tbody>
</table>

每当我单击加号图标时,都会引发 404 错误。即使在 IDE 中,app.js 中的第二个 when 的颜色也不同于第一个和 else() 的颜色。

编辑:还可以帮助我使用 $locationProvider,它在添加到 app.config() 时会引发此错误 - 错误:HTML5 模式下的 [$location:nobase] $location 需要存在标签!

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    你需要更新

    href="/new"
    

    href="#/new"
    

    【讨论】:

    • 这是一个 hack 还是它应该是这样写的?因为我遵循了该人之前没有使用 # 的教程。但使用 $locationProvider 设置 html5Mode(true) 。但是当我尝试这样做时,它会引发错误 - 错误:[$location:nobase] $location in HTML5 mode requires a tag to be present!
    • 这不是黑客。这是按照设计。您所指的是另一种实现事物的方式。如果你愿意,我也可以添加详细信息。
    • 请把它们也加进去。这对我很有帮助。
    • 我在stackoverflow.com/questions/27264754/…找到了答案,请检查。
    • 关于缺少&lt;base&gt; 标签的错误是正确的。您所要做的就是将其添加到您的index.html.....&lt;base href="/"&gt;
    猜你喜欢
    • 2014-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 2021-12-18
    相关资源
    最近更新 更多