简体   繁体   English

AngularJs-路由不起作用

[英]AngularJs - Routing does not work

it's the first time I am using AngularJs Routing, and I have a little bit of trouble with it. 这是我第一次使用AngularJs路由,但是有点麻烦。 I read similar question like mine here on stackoverflow, but I can't find my mistake. 我在stackoverflow上阅读了类似我的类似问题,但我找不到我的错误。

I created an self containing example, which I hope will help you find the bug. 我创建了一个自我包含的示例,希望对您有所帮助。 I published the example on github . 我将示例发布在github上 But to be complete I also posted the file contents below. 但是为了完整起见,我还在下面发布了文件内容。

Edit: 编辑:

To clarifiy what is the problem. 为了澄清问题所在。 I dont get a specific error message, but clicking on my menu will not change the view. 我没有收到特定的错误消息,但是单击菜单不会改变视图。 Instead it will always load the default view. 相反,它将始终加载默认视图。

Project Structure: 项目结构:

  • index.js index.js
  • package.json 的package.json
  • views 意见
    • manager 经理
      • dashboard.hbs dashboard.hbs
      • green.htm green.htm
      • main.htm main.htm中
      • red.htm red.htm
  • public 上市
    • css CSS
      • style.css style.css文件
    • js JS
      • DashboardController.js DashboardController.js

index.js: index.js:

const express = require('express')
const path = require('path')
const exphbs = require('express-handlebars')
const app = express()

app.set('views', path.join(__dirname, 'views'))
app.use(express.static(path.join(__dirname, 'public')))


app.engine('.hbs', exphbs({
    defaultLayout: false,
    extname: '.hbs',
    layoutsDir: path.join(__dirname, 'views', 'shared'),
    partialsDir: path.join(__dirname, 'views', 'shared')
}))

app.set('view engine', '.hbs')


app.get('/manager/dashboard',  function (req, res) {
    res.render('manager/dashboard')
})

app.listen(3000, function () {
    console.log('Example app listening on port 3000!')
})

dashboard.hbs: dashboard.hbs:

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Dashboard
    </title>
    <!-- load bootstrap css -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <!-- Add icon library -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    <link rel="stylesheet" href="/css/style.css">

    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
    <script src="/js/DashboardController.js"></script>
    {{!--
    <style>
        body {
            padding-top: 50px;
        }
    </style>--}}
</head>

<body ng-app="myApp">

    <div class="page language-en" id="welcome-page">
        <header class="clearfix">

        </header>


        <div class="container-fluid" >
            <div class="row">
                <div class="col-sm-1 icon-col">

                    <div class="icon-bar">
                        <a class="active" ng-href="#"><i class="fa fa-dashboard"></i></a>
                        <a ng-href="#orders"><i class="fa fa-shopping-cart"></i></a>
                        <a ng-href="#products"><i class="fa fa-dropbox"></i></a>
                    </div>

                </div>

                <div class="col-sm-11 ng-view">
                    <p> Dashboard </p>
                </div>

            </div>
        </div>

    </div>
</body>

</html>

DashboardController.js: DashboardController.js:

"use strict"

var app = angular.module("myApp", ["ngRoute"]);
app.config(function ($routeProvider) {
    $routeProvider
        .when("/manager/dashboard/", {
            templateUrl: "manager/main.htm"
        })
        .when("/manager/dashboard/orders", {
            templateUrl: "manager/green.htm"
        })
        .when("/manager/dashboard/products", {
            templateUrl: "manager/red.htm"
        }).otherwise({
            template: "<h1>None</h1><p>Nothing has been selected</p>"
        });

});

app.run([
    '$rootScope',
    function ($rootScope) {
        // see what's going on when the route tries to change
        $rootScope.$on('$routeChangeStart', function (event, next, current) {
            // next is an object that is the route that we are starting to go to
            // current is an object that is the route where we are currently
            if (current.originalPath && next.originalPath) {
                var currentPath = current.originalPath;
                var nextPath = next.originalPath;

                console.log('Starting to leave %s to go to %s', currentPath, nextPath);
            }

        });
    }
]);

app.run([
    '$rootScope',
    function ($rootScope) {
        // see what's going on when the route tries to change
        $rootScope.$on('$locationChangeStart', function (event, newUrl, oldUrl) {
            // both newUrl and oldUrl are strings
            console.log('Starting to leave %s to go to %s', oldUrl, newUrl);
        });
    }
]);

app.run(function ($rootScope) {
    $rootScope.$on('$routeChangeError', function (evt, current, previous, rejection) {
        console.log('Route error', rejection);
    });    
});

style.css: style.css中:

.icon-bar {
    width: 40px; /* Set a specific width */
    background-color: #555; /* Dark-grey background */
    height:100vh;
}

.icon-bar a {
    display: block; /* Make the links appear below each other instead of side-by-side */
    text-align: center; /* Center-align text */
    padding: 10px; /* Add some padding */
    transition: all 0.3s ease; /* Add transition for hover effects */
    color: white; /* White text color */
    font-size: 15px; /* Increased font-size */
}

.icon-bar a:hover {
    background-color: #000; /* Add a hover color */
}

.icon-col{
    padding-left:0px;
}

.active {
    background-color: #4CAF50; /* Add an active/current color */
}

html, body, .container-fluid, .row {
    height: 100%;
}

green.htm, red.htm, main.htm green.htm,red.htm,main.htm

<h1>placeholder-name</h1>

As per the AngularJs model All file should be in the static directory. 按照AngularJs模型,所有文件应位于静态目录中。

$routeProvider
    .when("/manager/dashboard/orders", {
        templateUrl: "manager/main.htm"
    });

This code will try to load the path like 这段代码将尝试像这样加载路径

[localhost:port/manager/dashboard/orders]

Which is GET request to the NodeJs Server and you haven't define any route for that. 这是对NodeJs Server的GET请求,您尚未为此定义任何路由。

so simply PUT all the files which you want to load through angular in a "PUBLIC" directory as you defined it as a static directory. 因此,只要将您要定义的所有文件定义为静态目录,就可以通过“ PUBLIC”目录中的angular来放置所有要加载的文件。

app.use(express.static(path.join(__dirname, 'public')))

And pass all the GET request which are not defined in your express Router like below by redirecting traffic to dashboard OR just create all your website in angularJs ignore handlebar. 并通过将流量重定向到仪表板来传递您在特快路由器中未定义的所有GET请求,如下所示,或者仅在angularJs中创建所有网站而忽略车把。

app.get('*', (req, res) => {
   res.render('manager/dashboard');
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM