Tips for creating an angularjs login page as the initial page

I am new to working with AngularJS and I have been experimenting with the generator-angular-fullstack,

My goal is to have the login page load first instead of the main page. After playing around with the code, I found a solution by adding 'authenticate: true' in MainCtrl

angular.module('myapp')
  .config(function ($stateProvider) {
    $stateProvider
      .state('main', {
        url: '/',
        templateUrl: 'app/main/main.html',
        controller: 'MainCtrl',
        authenticate: true
      });
  }); 

I also commented out the line 'event.preventDefault();' in app.js within the run function

.run(function ($rootScope, $location, Auth) {
    // Redirect to login if route requires auth and you're not logged in
    $rootScope.$on('$stateChangeStart', function (event, next) {
      Auth.isLoggedInAsync(function(loggedIn) {
        if (next.authenticate && !loggedIn) {
          //event.preventDefault();
          $location.path('/login');
        }
      });
    });

Although my approach seems to work fine, I'm unsure if these changes are the best solutions or if there are other alternatives available.

Answer №1

To achieve this, your code structure should follow the example below:

Inside main.js

 angular.module('myapp')  
       .config(function ($stateProvider) {
        $stateProvider
          .state('main', {
            url: '/main',
            templateUrl: 'app/main/main.html',
            controller: 'MainCtrl'
          });   
      });

In account.js

    angular.module('myapp')
      .config(function ($stateProvider) {
        $stateProvider
          .state('login', {
            url: '/',
            templateUrl: 'app/account/login/login.html',
            controller: 'LoginCtrl'
          })
          .state('signup', {
            url: '/signup',
            templateUrl: 'app/account/signup/signup.html',
            controller: 'SignupCtrl'
          })
          .state('settings', {
            url: '/settings',
            templateUrl: 'app/account/settings/settings.html',
            controller: 'SettingsCtrl',
            authenticate: true
          });
      });

Within login.controller.js

angular.module('myapp')
  .controller('LoginCtrl', function ($scope, Auth, $location, $window) {
    $scope.user = {};
    $scope.errors = {};

    $scope.login = function(form) {
      $scope.submitted = true;

      if(form.$valid) {
        Auth.login({
          email: $scope.user.email,
          password: $scope.user.password
        })
        .then( function() {
          // Successfully logged in, directing to home page
          $location.path('/main');
        })
        .catch( function(err) {
          $scope.errors.other = err.message;
        });
      }
    };

    $scope.loginOauth = function(provider) {
      $window.location.href = '/auth/' + provider;
    };
  });

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

Retrieving data arrays from response.json

I've been on a wild goose chase trying to solve this puzzling issue. RAWG has transitioned to using their own API instead of Rapid API for game reviews, and I'm in need of data for "Tom Clancy Rainbow Six Siege". Despite my efforts to convert t ...

Tips for removing the pound sign from a URL using AngularJS

Currently, I am utilizing AngularJS 1.3 for my project. The URL for my project can be accessed at http://localhost/MyProject/app/#/index.html. However, I aim to open the index.html file specifically at the URL http://localhost/MyProject/index.html. Could s ...

Strategies for resolving the error "Cast to ObjectId failed for value"

<form action="" method="post"> <input type="password" name="password" placeholder="Type Your Password Here" required> <input type="hidden" name="user_id" value=&q ...

What is the best way to perform an AJAX request on Hackerrank using JavaScript?

As I dove into the Hackerrank example test, I experimented with various methods for making an AJAX call. XMLHttpReq, fetch, and others were attempted but none seemed to work; both XHR and fetch methods were unavailable. My first attempt was with fetch: as ...

What is the best way to handle parsing JSON using external middleware after the removal of body parser in Express?

Having trouble parsing JSON with external middleware after Express removed the body parser? I used to rely on Express bodyParser for handling JSON posts, but after updating Express, my JSON requests are returning null. It seems like I was using the wrong ...

How can AngularFire update data without needing to retrieve the existing values?

Is it possible to update data by adding a number to existing data in the database, or is it necessary to retrieve the initial data first and then add the number to it? For example: this.db.object('something').update({ current:+1 // for ...

Ensuring that two operators are not consecutively placed in a Javascript calculator-validation guide

After creating a basic calculator using HTML, CSS, and JavaScript, I encountered an issue. When validating user input, the calculator currently accepts multiple operators in a row. To address this, I attempted to prevent consecutive operators by checking ...

Two distinct iterations of the identical jquery version sourced from external sources

NOTE: This situation involves having two copies of jQuery with the same version number but different libraries loaded by external sources. This is distinct from the issue of using multiple versions of jQuery on a single page, as discussed here: Can I use m ...

I am interested in utilizing Google Apps Script (GAS) to store images in GoogleDrive and automatically populate the corresponding URL in a

Currently, I am utilizing GoogleAppsScript to develop a form for submitting names and images. The idea is to store the submitted name and image in GoogleSpreadSheet while also storing the image in GoogleDrive along with its destination URL. The process inv ...

Modify the image source using Javascript

I need to update the src attribute of an image in a parent element nested within a ul li when a link is clicked. Here's my code so far. I know how to use JavaScript to change the src attribute, but I'm not sure how many levels I need to go up to ...

Retrieve JSON Data Using Angular in a Wordpress Environment

I need assistance with displaying a JSON Array in <li>'s within a Wordpress Template. Here is the specific JSON file: I am completely unfamiliar with how to achieve this. This is the HTML code I have: <div ng-app="appExtern" ng- ...

Display requested tab feature using jQuery upon page load

I am new to jquery and have been using this code for creating tabs: <script type="text/javascript" charset="utf-8> $(function () { var tabContainers = $('div.tabs > div'); tabContainers.hide().filter(':first&apo ...

Where should I place the .filter method within my jQuery AJAX call?

I'm currently utilizing a "GET" request to fetch data from this API While the "GET" request works properly, I'm facing an issue where some objects don't have image thumbnails to use as my source. I want to filter these out, but I'm uns ...

Changing HTML dynamically does not trigger the ng-click event within ng-bind-html

I have developed a custom directive that can display messages along with rendering HTML content that may contain Angular attributes like buttons, anchor tags with ng-click attribute, and more. index.html: <ir-error-panel status="status"></ir-err ...

MongoDB subfield pagination technique

I am looking to retrieve specific data from a sub-field in a MongoDB collection and implement pagination for it. Thank you! { "_id": "616d274c655e0000ee005f32", "subscription": [ { "account_admin&q ...

Is there a way to use JavaScript to rearrange the order of my div elements?

If I have 4 divs with id="div1", "div2", and so on, is there a way to rearrange them to display as 2, 3, 1, 4 using Javascript? I am specifically looking for a solution using Javascript only, as I am a beginner and trying to learn more about it. Please p ...

Using Laravel for login with the option to choose from multiple usernames

I am looking to enhance my Laravel VueJS application by allowing users to log in using their username and registration number instead of just an email. I have successfully implemented this functionality by modifying the username function within the Authent ...

Initiate a POST request to download the file upon clicking the button

How can I initiate a file download when a button is clicked? During testing, I noticed that sending a GET request using <Link href="/api/generate-pdf"> works perfectly and the PDF file gets saved. However, when I use a button to hit the API, the dow ...

Showing all elements on page load that are currently being filtered out in React

I've created a page that displays a grid of images with various details like title, description, author, and more. All this data is being pulled from my SQL table (referred to as marketplaceData). To enhance user experience, I added a search bar to f ...

AngularJS: Retrieving the sequence of choices in md-select with multiple selections

After choosing two options in the <md-select>, I am presented with an array of those two values. However, my query lies in how to determine the order in which these selections were made. As demonstrated in this codepen example, if I choose One first ...