Navigating with Angular - sending users to an external webpage?

When working with AngularJS routes, there is the option to use an otherwise route as a replacement for a 404 error:

$routeProvider
.when(...)
.otherwise({
    redirectTo: 'my/path'
});

Is it possible to configure the otherwise route to redirect to a page that is outside of the application? I attempted to accomplish this by using:

$routeProvider
.when(...)
.otherwise({
    redirectTo: 'http://example.com'
});

However, this simply tried to redirect to that path within my app, which does not exist. The workaround that I am aware of involves manually handling redirection in a $scope.$on('$routeChangeStart') event listener in a top-level controller, but this approach results in code duplication and is considered unsightly. Is there a more efficient solution available?

Answer №1

From my understanding, achieving this might be challenging since the routeProvider is designed to handle internal routes exclusively.

However, a workaround could involve:

$routeProvider
.when(...)
.otherwise({
    controller: "404Controller",
    template: "<div></div>"
});

After that, you can simply use

window.location.href = 'http://yourExternalSite.com/404.html'
within the controller.

Answer №2

This solution proved to be effective for me personally:

$routeProvider
.when('/my-path', {
    ...usual configurations...
}).
.otherwise({
        redirectTo: function(obj, requestedPath) {
            window.location.href = appConfig.url404;
        }
});

Answer №3

Have you checked out this thread on how to disable deep linking for specific URLs in Angular.js? It might be helpful.

Here is a solution that you can use:

target="_self"

<a href="link" target="_self" >link</a>

Answer №4

Instead of solely relying on window.location.href in a new controller, I would caution against it as it can cause issues with ngRoute setting the history incorrectly, leading to constant redirection to a 404 page when users click back. I attempted this method and encountered failure.

For an alternative solution, I recommend checking out my response to a similar query on SO here:

I implemented that approach to address your situation. Utilizing MainCtrl outside of ng-view may not be a bad idea, especially if it is only declared once unless there are nested ng-view layers. There should be no code duplication concern, and you have the option to place MainCtrl in a separate module for better organization:

.config(['$routeProvider', function($routeProvider) {
  $routeProvider
  .when(..) 
  .otherwise({redirectTo: 'http://yourExternalSite.com/404.html'}); 
}])
.controller('MainCtrl',[ // <- Use this controller outside of the ng-view!
  '$rootScope','$window',
  function($rootScope,$window){
    $rootScope.$on("$routeChangeStart", function (event, next, current) {
      // next.$$route <-not set when routed through 'otherwise' since none $route were matched
      if (next && !next.$$route) {
        event.preventDefault(); // Stops the ngRoute to proceed with all the history state logic
        // We have to do it async so that the route callback 
        // can be cleanly completed first, so $timeout works too
        $rootScope.$evalAsync(function() {
          // next.redirectTo would equal be 'http://yourExternalSite.com/404.html'
          $window.location.href = next.redirectTo;
        });
      }
    });
  }
]);

Cheers

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

rely on a fresh event starting at one

Despite my limited knowledge in javascript, I managed to create a simple js calendar that I am quite proud of. However, I have been facing a challenge for the past few days. You can view my calendar here: https://jsfiddle.net/ck3nsemz/ The issue I'm ...

Is it possible for a React application to manage errors (status code 4xx) using a try-catch block

Currently delving into React (using hooks) and facing an interesting challenge. I am in the process of building a Notes Application (from FullStackOpen's learn react section). The database I'm working with only allows notes with content length gr ...

Every time I attempt to run "npm install" on Visual Studio Code, I encounter an error

Every time I try to run npm install, I encounter this error. My node version is 18.9.1 and I have exhausted all possible solutions. Any help would be greatly appreciated. '''npm ERR! code ENOENT npm ERR! syscall open npm ERR! path C:\Us ...

How do I insert a new item into the tree structure using Sapui5 CustomTreeItem?

Having an issue with the CustomTreeItem in SAPUI5. I can successfully display the tree structure from JSON, but struggling to manually add data on click of the Add button. In the image above, when I click the + Button, I need to add a Tile below it. Howev ...

Tips for utilizing both the Element Selector and Class Selector in Jquery

I am working with a simple table that has TDs assigned either the 'PLUS' or 'MINUS' class. My goal is to use jQuery to implement functionality for collapsing all or expanding all. When the Expand All button is clicked, I need to chang ...

Prevent global CSS from being overridden in a production environment for a React Next.js application

Being new to REACT-NEXT and coming from an Angular background, I am struggling with fixing this issue. Here is the element I am using from another resource: import example-custom-ele-parent, {example-custom-ele-child} from 'custom-tags/example-custom& ...

Quick tip on closing an Angular-ui modal from a separate controller

I am currently using Angular-ui to display a modal with a form inside. Here is the code snippet: app.controller('NewCaseModalCtrl', ['$http', '$scope','$modal', function ($http, $scope, $modal, $log) { $scope.ite ...

Transparent background with opaque text

I noticed that my div has a gray background with some opacity. <div className="absolute w-full h-full top-0 left-0 right-0 bottom-0 bg-slate-500 opacity-50 z-10"> <p className="relative top-1/2 px-8 text-center hea ...

Tips for generating AJAX requests directly from HTML documents

Hey there! I'm fairly new to JavaScript and have a question that might seem silly to some. How exactly can I invoke a function from a Coffeescript file within my HTML code? I'd like to give users the option to choose the language in which they v ...

Retrieve data from an SQL database and populate an HTML dropdown menu in a web page using PHP

I am a beginner in the world of JavaScript and facing some challenges. I am working with PHP 7 and attempting to retrieve data from an SQL database, specifically a table. My goal is to extract a single column from this table and display it in a dropdown me ...

Angular displaying a slice of the data array

After following the example mentioned here, and successfully receiving API data, I am facing an issue where only one field from the data array is displayed in the TypeScript component's HTML element. Below is the content of todo.component.ts file im ...

What is the process for installing fontawesome using npm?

I encountered an error while attempting to install that looks like the following: $ npm install --save @fortawesome/fontawesome-free npm WARN saveError ENOENT: no such file or directory, open 'C:\Users\Admin\Desktop\package.json&a ...

Definition of TypeScript type representing the value of a key within an object

As I delve into defining custom typings for a navigation library using TypeScript, one challenge that has me stumped is creating a navigate function. This function needs to take the Screen's name as the first argument and the Screen's properties ...

Is there a way to make images load only when the navigation buttons are clicked in a scrollable (jquery tools) rather than loading all images at once?

I came across this great demo tutorial that I'm currently following: The issue with the tutorial is that it loads all the images at once, which significantly impacts performance. My goal is to have it load a set of images each time you click the arro ...

What is the best way to choose a random ID from a table within specified time intervals in MySQL?

I need to retrieve a random ID from the table nodes within the last 15 seconds. I attempted the following code, but it produced a lengthy output: const mysql = require('mysql'); const connection = mysql.createConnection({ host ...

Guide to Incorporating a Marker into an SVG Blinking Rectangular or Circular Border Image on Google Maps

I have a link that points to a specific location on Google Maps using latitude and longitude: http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png Now, I am looking to add a blinking border to this marker link. Is there a way to achieve this ...

Tips for arranging elements in proper order following a rotation

Having trouble aligning rotated divs? Let's say we rotate .straight by 30deg, and now we want to find the new offset coordinates of its bottom right corner. This way, we can perfectly match up the bottom left corners of .curve with this new coordinate ...

Creating an infinite scroll with a gradient background: a step-by-step guide

I am currently working on a project to develop an infinite scrolling webpage with a dynamic gradient background that changes based on the user's scroll position. While researching, I came across some code for infinite scrolling using time and date. I ...

What is the best way to make a drop down menu list appear when I click on the parent li, and then show the sub li using JavaScript?

I have a code that includes an image, HTML, and CSS code. Can anyone please tell me how I can set up a drop-down menu list to open the sub <li> elements when I click on a parent <li> using JavaScript? You can see the appearance of the code in t ...

Using GeoJson in Leaflet for map display

As I develop an Angular application with Leaflet, my goal is to showcase numerous municipalities within my country: https://i.sstatic.net/9cuSW.png In order to enhance navigation efficiency, I decided to divide my JSON file into multiple files and store ...