AngularJS app experiencing issues with routing

I'm currently working on an angularjs app, but unfortunately my routing functionality is not functioning correctly.

After logging into the application using Login.html, it should redirect to index.html, but for some reason it's not working as expected.

Here's a snippet of my app.js:

/**
 * Created by gupta_000 on 7/19/2016.
*/
'use strict';
var myApp = angular.module('myApp',[
'Controllers','ngRoute'
]);
myApp.config(['$routeProvider',
function($routeProvider) {
    $routeProvider.
    when('/main', {
        templateUrl: 'Login.html',
        controller: 'LoginCtrl'
    }).
    when('/home/student', {
        templateUrl: 'index.html',
        controller: 'DictionaryController'
    }).
    otherwise({
        redirectTo: '/main'
    });
}]);

All my custom files can be found at the location provided below.

http://plnkr.co/edit/mi2JS4y2FfMD9kIl58q?p=catalogue

I have made sure to include all the necessary dependency files such as angular.js and angular-route.js.

Thank you in advance for any help or suggestions.

Answer №1

Check out this interactive Plunker showcasing your code. A crucial element you're missing is the ng-view, which ngRoute utilizes to swap content based on your configuration. In essence, your index.html should resemble:

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    <ng-view></ng-view>
  </body>

Essentially, ng-view serves as an Angular directive that injects the current route's template (/main or /home/student) into the primary layout file. To elaborate, it fetches the corresponding file based on the route and embeds it within the main layout (index.html).

In your setup, 'main' in ng-view corresponds to Login.html within the config. I've tweaked '/home/student/' to map to a distinct page 'dic.html' to prevent an endless loop previously tied to index.html

var app = angular.module('plunker', ['ngRoute', 'Controllers']);

app.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
    when('/main', {
      templateUrl: 'Login.html',
      controller: 'LoginCtrl'
    }).
    when('/home/student', {
      templateUrl: 'dic.html',
      controller: 'DictionaryController'
    }).
    otherwise({
      redirectTo: '/main'
    });
  }
]);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
});

Similar to your scenario, upon logging in with credentials like 'harish' for both email and password, the successCallback triggers navigation to '/home/student', replacing ng-view with dic.html:

 $scope.validate = function() {
      $http.get('credentials.json').then(function successCallback(response) {
        // this callback will be called asynchronously
        // when the response is available
        console.log('Data: ' + JSON.stringify(response));
        $scope.users = response.data;

        var count = 0;
        for (var i = 0, len = $scope.users.length; i < len; i++) {
          if ($scope.username === $scope.users[i].username && $scope.password === $scope.users[i].password) {
            alert("login successful");
            count = count + 1;
            if ($scope.users[i].role === "student") {
              $location.path('/home/student');
              break;
            }
          }
        }

        if (count != 1) {
          alert("Please provide valid login credentials");
          $location.path("/main")
        }

      }, function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        console.log("Error: " + JSON.stringify(response));
        alert(JSON.stringify(response));
      });

    };

If you require further assistance, feel free to reach out.

Answer №2

To properly set up your Angular app, make sure to include the ng-view directive within the ng-app in your index.html.

Here's an example:


    <body ng-app="myApp">
        <ng-view></ng-view>
    </body>

By following this structure, your Angular app will load the view template and controller based on the routes configuration specified inside the ng-view directive.

It's also recommended to have a single generic index.html file where you can include all dependencies and render templates with their respective controllers according to the routes configurations. This helps avoid redundancy of including dependencies multiple times across different files, such as what was done with separate index.html and login.html.

Answer №3

Your controller is missing the injection of $location.

app.controller('MainCtrl', function($scope, $http, $location) {
  $scope.message = 'Hello';
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The functionality of the AngularJS custom directive and controller method seems to be malfunctioning, as they are failing to trigger breakpoints in

There seems to be an issue with the custom directive and controller method in AngularJS that are supposed to handle the visibility of the md-fab scroll-back-to-top button. The button should become visible when the page is scrolled down and hide when it rea ...

Arrange the items in AngularJS using ng-repeat from horizontal to vertical orientation

I am currently using ng-repeat on floated left <li> elements, resulting in a horizontal list. Is there a way to repeat the same items vertically as shown below? from: Item1 Item2 Item3 Item4 Item5 Item6 Item7 Item8 Item9 Item10 to: Item1 ...

Ways to prevent the Layout component from rendering on the NextJS login page

Is there a way to prevent the rendering of the Layout component in NextJS when the route is /login, /register, etc? const MyApp = ({ Component, pageProps }) => { return ( <Layout> <Component {...pageProps} /> </Layout> ...

Next.js pages do not respond to event listeners

Something strange is happening in my Next.js project. I've implemented a header that changes color as the page scrolls using the useEffect hook: The hook in the Header component looks like this: React.useEffect(() => { window.addEventListener(&a ...

What is the best way to pull HTML content and insert it into a div container?

Can someone help me with transferring simple HTML content into another DIV? Whenever I try, all I get is [object HTMLDivElement]. What mistake am I making here? this.inner = document.querySelector('div[data-v="1"]') this.tail = document.querySel ...

Encountering a server issue while incorporating ejs in expressjs

I am a beginner with nodejs and I am experimenting with using ejs to template my website. However, every time I try to set the view engine, I encounter the error 500 - Internal Server Error. Here is my app.js: var express = require('express'); v ...

Tips for handling a series of JSON responses in JavaScript in real-time without having to wait for the final response

Is it possible to send an HTTP request from JavaScript to a URL that will generate multiple JSON responses over time, and then handle those responses as they are received by the client? I am looking to test a series of Flash streams in PHP on the server t ...

Is there a way to create a new prettyphoto window by clicking on a link within the original prettyphoto window?

I have an HTML table that is dynamically constructed on the server side using AJAX. The table is displayed using prettyphoto, everything works fine up to this point. However, the last column of the table contains a link that should open an image using pret ...

Does setting the hours to 12 with Javascript turn the date back by one day?

Something strange is going on. I have a Date object: 2015-10-13T00:00:00.000Z When I run this function: date.setHours(12, 0, 0, 0); I'm seeing this unexpected result: 2015-10-12T19:00:00.000Z What could be causing this unusual behavior? ...

jQuery Cycle - extra images

Having an issue with the jQuery Cycle Plugin. I was able to set up the standard cycle, but now I want 3 images to appear at the start of a single slideshow. Any assistance would be greatly appreciated! Thank you ...

Issue encountered when setting a background image in Angular

When trying to add a background image and set it to cover the entire browser window, I encountered an issue where the image appeared very small and did not fully cover the background. As someone new to Angular, my understanding of how this process works i ...

Calculating the duration between two dates using momentjs and the angular-bootstrap Datepicker

I have integrated 2 Datepickers from angular-bootstrap. Using moment.js for calculating the difference between these Dates. By default, there is a 20-hour difference between the Dates when starting the App, and this calculation works correctly. However, I ...

What is the alternative way to achieve this functionality in Javascript without relying on jQuery?

I am encountering some dependencies issues with jQuery that are preventing me from using it. However, I still need to find a way to make this work without relying on jQuery libraries. Do you have any suggestions on how to achieve this? $(document).ready ...

Issue with Material UI Tab component not appearing in the first position

I've encountered an unusual problem where the first tab is not displaying correctly. To troubleshoot, I added a second tab which appeared perfectly fine. After setting up the second tab to have the desired content of the first tab, I deleted the origi ...

Changes in date format using jQuery datepicker

I am having trouble with the code below. Whenever I attempt to change the date, it switches from 15/5/2012 to 05/15/2012. <script> $(document).ready(function(){ $("#date").datepicker({ }); var myDate = new Date(); var month = myDa ...

Adjusting the amount of rows and columns in a fluid manner with CSS grid (updated)

After conducting my research, it seems that the most effective way to set the final value of a CSS grid is either by directly specifying it or by creating/manipulating the css :root value. A similar query was previously raised here, although the answers p ...

I'm curious about integrating Font Awesome into my React.js project - any tips on

I'm having trouble getting Font Awesome to display in my React JS project. Here is the code I am using: import React, {Component} from 'react' import './category.css' import axios from 'axios' import Course from './c ...

Importing a CSV file from the web (Google Sheets) and converting it into a JavaScript array

I am working with a Google spreadsheet ( https://docs.google.com/spreadsheet/ccc?key=0Agymc2_-gI59dGxvRnZoRzNuNENIUE9kZ0h6WExxSXc&usp=sharing ) where I store my golf scores after each round. My goal is to import this data into my JavaScript file and ...

What is the most effective way to import a person's entire Steam inventory and determine the prices of each item for display on my website?

Currently, I am running a Node.js server and facing an issue with loading user inventory to display their items along with the values of each item using JavaScript. My current approach involves making multiple XHR requests - one for the user's items a ...

Using the -g flag in Node.js consistently results in error messages

Whenever I attempt to install something globally with node, I encounter a series of errors. Interestingly, when I tried it in Powershell, no errors were thrown, but I suspect this is due to the fact that I was using Powershell instead of the official Node ...