TruckerCat
TruckerCat

Reputation: 1487

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. I read similar question like mine here on stackoverflow, but I can't find my mistake.

I created an self containing example, which I hope will help you find the bug. I published the example on 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
  • package.json
  • views
    • manager
      • dashboard.hbs
      • green.htm
      • main.htm
      • red.htm
  • public
    • css
      • style.css
    • js
      • DashboardController.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:

<!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:

"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:

.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

<h1>placeholder-name</h1>

Upvotes: 1

Views: 68

Answers (1)

Shivam Mishra
Shivam Mishra

Reputation: 1856

As per the AngularJs model All file should be in the static directory.

$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.

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.

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.

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

Upvotes: 2

Related Questions