What are the steps for getting started with AngularJS?

I am new to AngularJS and JavaScript. I am struggling to understand how to handle the process of $cookiStore isUndefined. Here is the code snippet from my app.js file:

angular.module('postLogin', ['ngCookies'])
.config(function($routeProvider, $locationProvider){
    $routeProvider.when('/', {templateUrl: "index.html"});
    $routeProvider.when('/success', {templateUrl: "success.html"});
})

.controller('PostController', ['$scope', '$cookieStore', '$http', '$location', function($scope, $cookieStore, $http, $location) {        
        this.postForm = function() {
            var encodedString = 'username=' +
                encodeURIComponent(this.inputData.username) +
                '&password=' +
                encodeURIComponent(this.inputData.password);

            $http({
                method: 'POST',
                url: 'userauth.php',
                data: encodedString,
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            })

            .success(function(data) {
                    //console.log(data);
                    if ( data.trim() === 'one') {
                        $cookieStore.put('username', 'admin');
                        window.location.href = 'success.html';
                    } else if ( data.trim() === 'two') {
                        $cookieStore.put('username', 'dika');
                        window.location.href = 'success.html';
                    } else {
                        $scope.errorMsg = "Username and password do not match.";
                    }
            })            
        }
        $scope.last = $cookieStore.get('username');
        //below is logout function in success.html
        $scope.go = function(){
        $cookieStore.remove('username');
        window.location.href = 'index.html';
        }
        if ($location.url() !== '/' && angular.isUndefined($scope.last)) {
        window.location.href = 'index.html';
        }
}]);

Here is the content of my success.html file:

<html>
<h1> Success: Welcome to our website. </h1>
<head>
<script src="angular.min.js"></script>
<script src="angular-cookies.min.js"></script>
</head>
<body ng-app="postLogin" ng-controller="PostController">
{{last}}
<div class="buttons">
<input type="submit" class="button" ng-click="go()" value="click me">
</div>
<script src="app.js"></script>
</body>
</html>

Lastly, here is the content of my index.html file:

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8"/>
      <meta name="robots" content="noindex"/>
      <title>angulrjs login page</title>
      <meta name="viewport" content="width=device-width, initial-scale=1"/>
      <link href="css/style.css" rel="stylesheet" id="main-css"/>  
      <script src="angular.min.js"></script>
      <script src="angular-cookies.min.js"></script>
   </head>
   <body ng-app="postLogin" ng-controller="PostController as postCtrl">
      <div class="container">
         <div id="loginbox" class="mainbox col-md-6 col-md-offset-3 col-sm-6 col-sm-offset-3">
            <div class="panel panel-default" >
               <div class="panel-heading">
                  <div class="panel-title text-center">Login using username & password</div>
               </div>
               <div class="panel-body" >
                  <form name="login" ng-submit="postCtrl.postForm()" class="form-horizontal" method="POST">
                     <div class="input-group">
                        <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                        <input type="text" id="inputUsername" class="form-control" required autofocus ng-model="postCtrl.inputData.username"/>
                     </div>
                     <div class="input-group">
                        <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
                        <input type="password" id="inputPassword" class="form-control" required ng-model="postCtrl.inputData.password"/>
                     </div>
                     <div class="alert alert-danger" ng-show="errorMsg">
                        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">
                        ×</button>
                        <span class="glyphicon glyphicon-hand-right"></span>&nbsp;&nbsp;{{errorMsg}}
                     </div>
                     <div class="form-group">
                        <div class="col-sm-12 controls">
                           <button type="submit" class="btn btn-primary pull-right" ng-disabled="login.$invalid">
                           <i class="glyphicon glyphicon-log-in"></i> Log in</button>
                        </div>
                     </div>
                  </form>
               </div>
            </div>
         </div>
      </div>
      <script src="app.js"></script>
   </body>
</html>

I am encountering an issue with the loop in my index.html file due to $scope.last being undefined or null. How can I fix this problem and make it act like an !isset in PHP which I am more familiar with?

Answer №1

When checking for Undefined within the context of $scope.last, make sure to also verify if the current page is not already set to index.html. To achieve this, utilize the $location service in the following manner:

if ($location.url() !== '/' && angular.isUndefined($scope.last)) {
        window.location.href = 'index.html';
}

Important: Remember to inject the $location service into the PostController.

I hope this explanation proves to be beneficial for you!

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

Encountering an issue when bundling an application using electron-forge: "Unable to find solution for './→' "

Having trouble packaging my Electron application using electron-forge. It seems like the issue lies with native modules such as 'sqlite3'. Upon running the command npm run package, I encounter this error: Module not found: Error: Can't reso ...

Restart the calling process using NodeJS command

Is there a way to automatically restart the calling process in case certain events occur while querying a database? I want the process to start over if specific conditions are met. ...

What is the best way to perform calculations within a PHP loop for <input> elements and then display the results using a JavaScript loop?

Hello everyone, I'm currently struggling with displaying the calculations from a loop of input tags. What I'm trying to achieve is having 5 rows with input fields. At the end of each row, there should be a span area that displays the calculation ...

Manipulating and transforming data through Puppeteer's iterative process into an object structure

As a beginner with the puppetteer library, I'm trying to iterate through Amazon reviews and save each comment as an object. Although my code seems to be functioning, it only retrieves the first comment and then stops. async function scrapeProduct(ur ...

Tips for determining what elements are being updated in terms of style

I need assistance with modifying the functionality of a webpage's dropdown menu. Currently, it displays when the mouse hovers over it, but I want to change it to appear on click using my own JavaScript. Despite setting the onmouseout and onmouseover e ...

Utilizing Vue-cli 3: Incorporating static assets with a specific path

My application is located at: https:/firstpath.com/firstsubfolder/app.html When using relative paths, my static assets are being loaded from: https:/firstpath.com/firstsubfolder/img/image.png Is there a way to specify a specific path for my static asse ...

Searching for an individual MongoDB document using Express

I recently started working with MongoDB and express. I am trying to authenticate a user based on their username and password, but my code seems to always execute the "else statement" even when the correct credentials are entered. Below is the JavaScript f ...

The <g> tag fails to properly render within the <svg> element in Firefox

When running an Angular 6 application with ES6-style D3js modules, there are some issues on Firefox (Chromium, Chrome, Safari, and IE Edge work fine). Below is a sample of pseudo code (full production code is available below): <svg width="500" height=" ...

The communication between Angular 2 and ASP.net Core via a POST request is not functioning properly, as the server side is receiving a null value

Backend, ASP.net Core API: [Produces("application/json")] [Route("api/[controller]")] public class StoriesController : Controller { public static List<Story> STORIES = new List<Story> { new Story ...

Updating $scope in AngularJS works in JavaScript, but the changes are not reflected in the HTML

After making a request to the server and receiving a correct response, I have an array of objects called $scope.photos. However, when attempting to add a new photo by sending a request and then trying two different methods to update the $scope in the HTML, ...

The integration of query, URL, and body parameters is not working as expected in Seneca when using Seneca

I'm facing some difficulties with Seneca and seneca-web as a beginner. This is the current state of my code: "use strict"; var express = require('express'); var Web = require("seneca-web"); var bodyParser = require('body-parser' ...

Attempting to insert a dynamic variable into a jQuery click event selector

I'm facing an issue where I am attempting to use a variable as a selector within a click event for a dynamically generated row in a table. When I manually enter the class name, the row click event works perfectly. However, when I try to use the variab ...

Insert fresh user information into the div

Learning JavaScript is a challenge I'm tackling. I have a question that may seem trivial, but any assistance would be greatly appreciated. I currently have this code: Javascript <script type="text/javascript"> function fn(){ var Name = ...

Decoupling the Angular frontend for UIs from the Yii backend's Controller and Model layers

My goal is to integrate an Angular frontend with a Yii backend in a way that Angular handles routing and views while Yii manages controllers, models, and database connections. Angular will make AJAX requests for data, which will be processed by the RESTful ...

JavaScript AJAX Event Listener

Currently seeking a way to intercept ajax events in JavaScript before any Ajax method is triggered. While there is an ajaxListener in JQuery that could work if all the ajax requests were from JQuery, unfortunately, they are not. So the question remains: ho ...

How can server-side JavaScript effectively guard against SQL injection attacks?

Interested in finding the most effective methods to prevent SQL injection. Imagine this scenario: the client side (index.html) has a form that sends an array of string values to your server-side page via $.ajax var data_to_be_submitted = { ...

What are the best practices for effectively testing directives that involve DOM manipulation?

My inquiry begins with a preliminary question: Is it advisable to perform unit testing on DOM manipulation within Angular directives? Consider, for example, the following cohesive linking function: function linkFn(scope, element) { var ribbon = eleme ...

Having trouble passing input values from the view to the controller in Angular?

Having an issue with sending data to the controller via my view. Below is a snippet of the code: <form ng-submit="submitMessage()"> <div class="form-group"> <input type="number" class="form-control input ...

Creating several Doughnut Charts within a single Canvas using Chart.js

Is there a way to display multiple layers of a doughnut chart simultaneously using Chart.js? Currently, I'm only able to see one layer at a time and the others become visible upon hovering over their position... If you have any insights on how to mak ...

Receiving an error when attempting to inject the Router in a component constructor without using the elvis operator

Upon launching my app, I desire the route /home to be automatically displayed. Unfortunately, the Angular 2 version I am utilizing does not support the "useAsDefault: true" property in route definitions. To address this issue, I considered implementing th ...