Exploring an alternative perspective on successful login in angular.js

Today was the beginning of my project to convert a website to angular.js. The main page is served by index.html and includes ng-view for other views such as login and signup. Working closely with a backend developer, I have successfully integrated a rest client to handle the JSON data. However, I am currently facing a challenge with implementing authentication on the login page. Upon successful login, I aim to display the dashboard view. I am looking for a front-end solution to achieve this for testing purposes only.
Below is a snippet of the code.
app.js

'use strict';

/**
 * @ngdoc overview
 * @name servicepriceApp
 * @description
 * # servicepriceApp
 *
 * Main module of the application.
 */
var myApp;
(function() {
    myApp = angular
        .module('servicepriceApp', [
            'ngRoute'
        ])
        .config(function($routeProvider) {
            $routeProvider
                .when('/signup', {
                    templateUrl: 'views/signup.html',
                    controller: 'SignupController'
                })

            .when('/login', {
                    templateUrl: 'views/login.html',
                    controller: 'LoginController'
                })
                .when('/dashboard', {
                    templateUrl: 'views/dashboard.html',
                    controller: 'DashController'
                })
                .otherwise({
                    redirectTo: 'views/signup.html'
                });
        });
})();

login.js

myApp.controller('LoginController', function($scope, $http) {

    $scope.login = function() {

        var data = {
            email: $scope.email,
            password: $scope.password
        };
        $http({
            url: site + '/company/login',
            method: "POST",
            transformRequest: encodeurl,
            data: data,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).success(function(data) {
            console.log(data);
        }).error(function(res) {

            console.log(res);

        });
    }
});

index.html

  <!doctype html>
<html class="no-js" ng-app="servicepriceApp">

<head>
    <meta charset="utf-8">
    <title> Service price</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">
    <link rel="stylesheet" href="styles/normalize.css">
    <link rel="stylesheet" href="styles/foundation.min.css">
    <link rel="stylesheet" href="styles/all.css">
    <link rel="stylesheet" href="styles/main.css">
    <!-- endbuild -->
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="large-12 columns">
                <ul>
                    <li><a href="#signup"> SignUp </a>
                    </li>
                    <li><a href="#login"> Login </a>
                    </li>
                    <li><a href="#dashboard"> Dashboard </a>
                    </li>
                </ul>
            </div>
        </div>

        <div ng-view></div>
    </div>
    <script src="lib/angular/angular.min.js"></script>
    <script src="lib/angular/angular-route.min.js"></script>
    <!-- build:js({.tmp,app}) scripts/scripts.js -->
    <script src="js/app.js"></script>
    <script src="js/controllers/signup.js"></script>
    <script src="js/controllers/login.js"></script>

</body>

</html>

signup.html

var site = "http://someurl.in:9009"
var encodeurl = function(obj) {
    var str = [];
    for (var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    return str.join("&");
}
myApp.controller('SignupController', function($scope, $http) {

    $scope.signup = function() {

        var data = {
            email: $scope.email,
            password: $scope.password
        };
        $http({
            url: site + '/company/signup',
            method: "POST",
            transformRequest: encodeurl,
            data: data,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).success(function(data) {
            console.log(data);

        }).error(function(res) {

            console.log(res);

        });
    }
});

Hopefully, this code snippet provides a good overview of the current progress. Thank you for your assistance in advance.

Answer №1

    To change the view, simply include the line $location.path("/dashboard");
    For example:


    $http({
                    url: site + '/company/signup',
                    method: "POST",
                    transformRequest: encodeurl,
                    data: data,
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                }).success(function(data) {
$location.path("/dashboard"); //this line directs to the dashboard.
                    console.log(data);

                }).error(function(res) {

                    console.log(res);

                });

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

Using Vue to make a REST API call in a JavaScript file

I have been trying to convert an Axios API call from a Vue page into a standalone module that can be reused multiple times in my app. Unfortunately, all my attempts so far have failed and I'm not sure if it's because I lack experience working wit ...

Ways to modify the values of a Bootstrap Dropdown using a unique identifier

Here is an example of a typical Bootstrap Dropdown: <div class="btn-group"> <button type="button" class="btn btn-lg btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Default option<span class ...

A guide on incorporating the input type 'date' for date columns in jqGrid

When using jqGrid for inline editing, a date column is defined in the colmodel with accompanying JavaScript code. However, it can be cumbersome to maintain and produces an unattractive result. In instances where the browser supports it, how can one utiliz ...

Tips for incorporating images as radio buttons

Can anyone assist me in setting up a straightforward enabled/disabled radio button grouping on my form? My idea is to utilize an image of a check mark for the enabled option and an X for disabled. I would like the unselected element to appear grayed out ...

I am in need of a datepicker for my project that will display the END date as the current date and set the START date as 7 days before the END date

$(document).ready(function () { $("#end").datepicker({ dateFormat: "dd-M-yy", minDate: 0, onSelect: function () { var start = $('#start'); var startDate = $(this).datepicker('getDate') ...

AngularJS and JQuery: smoothly navigate from current position to specified element

This particular directive I am currently implementing was discovered as the second solution to the inquiry found here - ScrollTo function in AngularJS: .directive('scrollToItem', function($timeout) { ...

Save the chosen rows in the appropriate manner

I am currently exploring the functionalities of ngGrid. The list contains various items that users can select. I want to ensure that the selected items are saved so that when users revisit the page, they see the same selections as before. You can view the ...

The $eval function encounters issues within an angular.js directive

In my quest to create an angular.js directive, I encountered a situation where clicking on a <span> element should turn it into an editable input. The code below accomplishes this task flawlessly, except in the scenario where the model is empty or ha ...

Persist a SQL entity to a document with the help of Node.js

I am looking for a way to store the data from the rows object either in a file or as a JSON file. app.get('/getposts', (req, res) => { mysqlConnection.query('Select * from posts', (err, rows, fields) => { if (!err) console.l ...

AngularJS gathers user database information from Firebase using the `$rootScope`

My goal is to retrieve user information from a database and make it accessible globally using $rootScope. Upon user sign-in, I have access to the user's email and uid. However, in order to retrieve additional user info from the database, I need to que ...

What benefits does the PageSpeed Service/Library provide for a Single Page Application (SPA)?

After facing challenges with optimizing my web pages manually based on PageSpeed Insights recommendations, I am eager to try out the new PageSpeed Optimization Library/Service. My website is a single page application (SPA) that uses AngularJS and follows ...

Having issues with ng-repeat not displaying any content

Let me describe the current situation I am facing: app.controller('ResourceController', function($scope, $sce){ var resourceData; $scope.data = ''; $scope.loadResources = function(){ $.get('con ...

Transform a checkbox input into two distinct buttons

I am trying to change the input checkbox that toggles between light and dark mode into two separate buttons. How can I achieve this functionality? Check out the demo here: https://jsfiddle.net/ot1ecnxz/1 Here is the HTML code: <input type="checkb ...

The callback function used for the database query did not provide any results

So here's a code snippet: module.exports.checkEmailInUse = (email) => { connection.query('SELECT `id` FROM `users` WHERE email = ?', [ email ], function(err, rows, fields) { console. ...

Dealing with 404 errors: The role of Nuxt.js and the srcDir option in handling URL

By incorporating the srcDir option into my nuxt.config.js file, I made the decision to transfer the pages, components, and layouts folders to the src directory. Below is how my configuration looks: module.exports = { srcDir: 'src', head: { ...

I encountered an error in JavaScript where the function .val() is not recognized on the selected answer, throwing

I'm trying to verify if the selected answer is correct and then add +1 to my user score. However, I'm struggling with why my code isn't functioning as expected. Can someone please point out where the bug is or if there's something else ...

What is the process for altering a variable within an Ajax function?

Scenario: I'm dealing with JSON data fetched from the backend which needs to be presented in a table format. To achieve this, I've created a string called tableOutputString and am populating it by iterating through the JSON response. Finally, I&a ...

Using AngularJS to toggle between two select dropdowns

I have two drop-down lists containing JSON data. <select class="form control" ng-model="fruitsName" ng-options="r.id as r.name for r in fruits"> <option value="">--Select---</option></select> $scope.fruits = [{'id': &apo ...

What causes Express Async Errors to produce unexpected outcomes?

I stumbled upon a fantastic npm package called Express Async Errors that is highly recommended in the documentation. However, when I try to implement it, my server crashes. Here is my Route handler code: Controller const { Genre } = require("../models"); ...

JavaScript pop-up purchase tooltips from MenuCool

I am relatively new to the world of web design and programming. I am putting in a lot of effort to learn as much as possible, but I am encountering difficulties with the tooltip JavaScript that I incorporated into my website Click here to visit my website ...