Navigate to a different page using AngularJS

Currently working on building a MEAN stack web page with a login system. Started off by focusing on the front-end development. The server is up and running, successfully loading the index.html page. However, encountering difficulty in redirecting to another page post successful login. Attempted using $state.go for navigation, but it requires full page load. Also tried $window.location.href but faced issues and ended up with a messy URL.

The base href in my index.html is set to "/"

Below is my login controller code:


var app = angular.module('SantaUTIApp', []);
app.controller('loginCtrl', function($scope, $window, $timeout) {


    $scope.showGreeting = false;
    var link = "https://" + $window.location.host + "/home";
    $scope.showInvalidUserPasswordMessage = function() {
        $scope.msg="Invalid Username or Password.";
        $scope.showGreeting = true;
        $timeout(function(){
            $scope.showGreeting = false;
        }, 10000);
    };

    $scope.login = function(){
        if($scope.user === '1' && $scope.password === '2')
            $window.location=link;
        else
            $scope.showInvalidUserPasswordMessage();
    };

});

Angular route configuration:


var app = angular.module('SantaUTIApp', ['ui.router']);

app.config(function($stateProvider, $locationProvider, $urlRouterProvider){

    $stateProvider
        .state('login',{
            url:'/',
            templateUrl: 'views/index.html',
            controller: 'loginCtrl',
        })
        .state('home',{
            url: '/home',
            controller: 'homeCtrl',
            templateUrl: 'views/home/home.html'
        });

    $locationProvider.html5Mode(true);
});

Seeking advice on the best method to navigate to the home page after a successful login. Any suggestions would be greatly appreciated as I have exhausted all options so far.

Answer №1

To properly redirect, follow this procedure

$window.location.href=link;

Here are some other options to consider:

1. If you have saved the login status in a service and prefer not to reload the entire SPA, utilize $location as it avoids a complete page reload when changing the browser URL. For page reload after URL change, resort to the lower-level API, $window.location.href.

var app = angular.module('SantaUTIApp', []);
app.controller('loginCtrl', function($scope, $location, $timeout) {


  $scope.showGreeting = false;
  var link = $location.protocol() + $location.host() + '/home';
  $scope.showInvalidUserPasswordMessage = function() {
    $scope.msg="Invalid username or password.";
    $scope.showGreeting = true;
    $timeout(function(){
        $scope.showGreeting = false;
    }, 10000);
  };

  $scope.login = function(){
    if($scope.user === '1' && $scope.password === '2')
        $location.path(link);
    else
        $scope.showInvalidUserPasswordMessage();
  };

});

2. Additionally, you can make use of Angular routing's $state feature.

Replace $window with $state in your controller, then trigger the redirect like this. Similar to $location, this method does not initiate a full page reload.

$state.go('home');

Note: If you still desire to use $window, wrap it within a timeout function.

$timeout(function() {
  $window.location.href= link;
});

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

How can I disable the onClick event for an image within a div in an onClick function?

Is there a way to disable click events for an image using its image id? For example, if the id is id12, I want to disable the click event. I attempted to use `unbind` but it appears that it only works if the event is bound using jQuery? ...

Having trouble retrieving dotenv variables within a node module

I am facing an issue with accessing dotenv variables from a nested node module using process.env.[VARIABLE]. My directory structure is as follows: root ├── .env └── server ├── server.js └── database ├── db.js ...

How can you toggle the visibility of a React component based on the user's device browser?

Seeking a solution to dynamically hide/show a component in a React/Nextjs/tailwind webapp based on the user's device type (e.g. desktop vs tablet vs mobile) due to differences in available keyboard keys (e.g. tab key not present on tablets and mobile ...

"Efficiently Browsing Through Various Links with the Help of Greasemon

My goal is to open approximately 25 hyperlinks from a single page. All of these hyperlinks include the text Free Win. I am looking for a solution that will open each individual link in a new tab within the browser. I have written a Greasemonkey script, ...

Utilize the toggle feature to modify data displayed from the database

My webpage displays data from a database using PHP, and it works well. However, I want to add functionality that allows users to edit the displayed information by toggling between text and input form. When a user clicks on an 'Edit' button, I wan ...

I keep encountering a 404 error page not found whenever I try to use the useRouter function. What could

Once the form is submitted by the user, I want them to be redirected to a thank you page. However, when the backend logic is executed, it redirects me to a 404 page. I have checked the URL path and everything seems to be correct. The structure of my proje ...

Efficient method for deleting a specific item from a JSON object in React.js

Within the REACT JS framework, I am managing a JSON object in the state component "myrecords". The items within this object are organized by their respective Company Names and have the following structure: { "Master Automotives": [ { ...

Disable sorting options in the Datatable ColumnFilterWidget

I'm currently working with datatables ColumnFilterWidget and I'd like to prevent the widget from sorting the values displayed in the select box. Despite trying the "bSort": false option of the ColumnFilterWidget, it doesn't seem to have any ...

What could be causing the page to not update the value?

<input name="birthday" type="text" value="{{vm.client.birthday | date:'dd.MM.yyyy'}}" ng-click="vm.selectDate()" readonly required/> function selectDate() ...

Maintain the values of the scope when transferring a template within ng-repeat

I have two sets of data displayed on the interface through ng-repeat Within this, I have included ng-include="template.html" <div> <div ng-repeat="item in items1"> <ng-include src="item.template"></ng-include> </div> ...

Utilizing AngularJS for capturing backspace key presses

I'm trying to capture a user's backspaces inside an input field. Here is what I've attempted: <input type="text" ui-keypress="{8:'removeTagOnBackspace()'}" ng-model="searchStudent" /> Then, in my controller, I added the fo ...

Why is the reference of `this` pointing to `o` in this scenario (o.method)() rather than the global object?

Let's consider the scenario with an object: var o = { prop: 3, method: function() {return this.prop} } My expectation was that calling (o.method)() would result in undefined, but instead it returned 3, indicating that the reference of this ...

Reorganizing asynchronous code into a nested synchronous structure in Meteor/React

Recently, I've been experimenting with running data fetching code in a container component and passing it to the display component in order to streamline my use of hooks and reduce load time. I've tested both await/sync and Meteor's wrapAsyn ...

What is the process for attaching an event to a datasource in YUI framework?

http://developer.yahoo.com/yui/datasource/#events Attempting to utilize the responseParseEvent, however, I'm unsure of how to connect it with my datasource object due to the lack of examples provided by YUI. Sidenote: Am I the only one who has obser ...

Tips for adjusting the time interval on an automatic slideshow when manual controls are in play

I'm having trouble with my slideshow. I want it to run automatically and also have manual controls, but there are some issues. When I try to manually control the slides, it takes me to the wrong slide and messes up the timing for the next few slides. ...

Enhancing Date formatting in Jquery Data tables following ASP.NET Serialization

Currently, I am facing an issue with formatting dates in a SQL database query that is being serialized by ASP and then converted to JSON for display in Datatables using JavaScript. Instead of the correct date format, I am seeing: /Date(1424563200000)/. I ...

Incorporating AngularJS into your current JavaScript code base

We have a JavaScipt project underway that could greatly benefit from incorporating AngularJS. However, due to the size of the project, completely rewriting it in Angular is not feasible. Does anyone have any suggestions or tips on how to integrate Angula ...

Cross-Origin Resource Sharing problem: "Preflight request response does not meet access control criteria"

I'm currently tackling a Vue.js/Nuxt.js project that involves sending API requests to 'https://app.arianlist.com'. However, I've encountered some CORS challenges and came across this error message: "Access to XMLHttpRequest at &ap ...

What is the reason why certain variables in req.body can be read by Express.js while others cannot?

Currently, I am not utilizing body-parser and it is clear that I need to incorporate it. My query pertains to the inconsistency in how my variables are being accessed through req.body without body-parser. Some of the variables display undefined values whil ...

Unusual actions when making a $.ajax call using the PUT method

When making a call to $.ajax, I use the following code: $.ajax({ type: 'PUT', url: model.url(), data: {task: {assigned_to: selected()}}, contentType: 'application/json' }) The function selected() returns an array. However, th ...