The $urlRouterProvider.otherwise function does not integrate smoothly with ui-router

I am currently using ui-router version 1.0.11 for AngularJs 1.x

The issue I am facing:

When a user enters an address like: /url/abcdef that is not in my route configuration, they should be automatically redirected to /products. This redirection works fine, but the problem arises when there are parameters in the URL of links within the /products page. For example, when I click on a product name, it redirects me back to the /products page. Everything works fine if I remove $urlRouterProvider.otherwise('/customers'); from the router configuration, but then I don't have a route defined for pages like /url/rtrtrt.

Here is my router code:

    var app = angular.module("productsApp", [
  "ui.router"

]);

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

    $urlRouterProvider.otherwise('/products');

    $stateProvider
      .state("home", {
        url: "/products",
        templateUrl: "/products.html",
        controller: "MainCtrl",

        resolve: {
          getAllP: function($http) {
            return $http.get("/products/get").then(function(res) {
              return res.data;
            });
          }
        }
      })

      .state("det", {
        url: "details/:pId/details",
        templateUrl: "p_details.html",
        controller: "productDetailCTRL",

        resolve: {
          prDet: function($http, $stateParams) {
            return $http
              .get("/products/id/" + $stateParams.pId + "/details")
              .then(function(res) {
                return res.data;
              });
          }
        }
      });

    $locationProvider.html5Mode(true);
    $locationProvider.hashPrefix("!");
  }
]);

Update: I attempted to add another state /error with an error page error.html. However, I encountered the same issue even on the products page. Clicking on a product redirected me to the /error page!!! I'm puzzled as to why this is happening.

Answer №1

you did not follow the correct code structure you need to move

$urlRouterProvider.otherwise(**'home'**);

    var app = angular.module("productsApp", ["ui.router"]);

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


            $stateProvider
            .state("home", {
                url: "/products",
                templateUrl: "/products.html",
                controller: "MainCtrl",

                resolve: {
                    getAllP: function($http) {
                        return $http.get("/products/get").then(function(res) {
                            return res.data;
                        });
                    }
                }
            })

            .state("det", {
                url: "details/:pId/details",
                templateUrl: "p_details.html",
                controller: "productDetailCTRL",

                resolve: {
                    prDet: function($http, $stateParams) {
                        return $http
                        .get("/products/id/" + $stateParams.pId + "/details")
                        .then(function(res) {
                            return res.data;
                        });
                    }
                }
            });

            $urlRouterProvider.otherwise('home');

            $locationProvider.html5Mode(true);
            $locationProvider.hashPrefix("!");
        }
]);

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

Selector that targets an attribute in the beginning of its value [name^=value]

When trying to match input fields by name, I encountered a challenge. The names consist of a base name plus square brackets, which the PHP interpreter converts into arrays. According to the jQuery API, the suggested selector is as follows: ":input[name^=f ...

The regular expression for validating credit card numbers is invalid due to a repetition error

Here is the regular expression I've been using to validate credit card numbers in JavaScript: var match = /^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|?(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])?[0-9]{11})|((?:2131|1800 ...

Add a JavaScript file into a PHP document

I've been searching for a solution in various forums, but the main answer I found doesn't seem to work for me. As someone new to Web development, I'm attempting to create a simple JavaScript program that takes a JSON string of products and ...

Guide to declaring variables using jQuery

Currently tackling a school project, I stumbled upon some online example solutions and managed to decipher most of the code. However, there is one line that has me puzzled. var $newTweet = $('<div class=tweet></div>'); My assumption ...

Looking for a three.js resource to enhance my project

Looking for guidance on how to import a .obj 3D model into three.js. Any information or tutorials available? ...

What is the best way to calculate the difference in days between two dates using Javascript?

While there are many questions similar to this one, I've noticed that most examples focus on calculating the absolute number of days difference. So, how exactly can I determine the number of relative days between a given date (in epoch seconds) and t ...

Using the v-model directive in Vue.js with a for loop is

I am facing a challenge where I need to implement a v-for loop with multiple components, but I am unsure how to add a unique v-model to each component that is generated within the loop. <template> <ProfilePasswordField v-for="(item, ind ...

Exploring Javascript's Standard Object: A Guide to Retrieving Two Elements

If I have a special data object: var data = []; data["Name"] = ["Janet", "James", "Jean", "Joe", "John"]; data["Number"] = [25, 22, 37, 19, 40]; Let's say I'm looking for the minimum number value, which is '19' in this case. How ...

Show angular variable data in a table based on their index

I have an array of angular variables with values like [ 170, 1, 130, 3, 134, 4.... and so on]. I would like to present these values in a table format where the even positioned values are shown in one column and the odd positioned values in another column. ...

"Enhancing User Experience with JavaScript Double Click Feature in Three.js

Currently, I have implemented a double click function that allows the user to double click on a car model, displaying which objects have been intersected such as wipers, grille, and tires. These intersections are listed along with the number of items the d ...

The load function within THREE.FileLoader is specifically designed to retrieve the textual content of the index.html file

I've been working on a small web project using the create-js-app tool. I am attempting to load a file named test.txt from my src directory. Here is the code from my main.js file: import * as THREE from 'three'; const loader = new THREE.Fil ...

Eliminate jQuery's delayed blinking effect with the use of an event

Utilizing the mouseenter and mouseleave events, I have implemented a functionality to add a button (not actually a button) to an <li>. However, there seems to be a problem with my code. The button appears and disappears on mouseleave and mouseenter, ...

Storing data on the server for your Cocos2d JavaScript game

I've been struggling with implementing a savegame option for my cocos2d JavaScript game. After following a tutorial from Ray Wenderlich (thanks, Ray!), I gave up on trying to do it client-side and am now looking into saving XML files to a web server w ...

Tips for determining the height of the entire webpage using jQuery

I attempted the following code: $(window).height(); $("#content").height(); However, it did not provide an accurate value. ...

JavaScript: Add an element to the precise middle of an array

Sorry if this is a repeat question, but I couldn't find the answer despite searching. Let's say there's an array of unknown length and you want to insert items at a specific position, such as the center. How can you achieve this? Here&apos ...

Diving into Angular2 template forms: unraveling the mysteries of the reset function

After going through the template forms tutorial in Angular2, I'm facing a bit of confusion regarding the behavior of the native reset JavaScript function on Angular2 ngModel. While it's not explicitly clarified in the official documentation, my u ...

The issue with the jQuery function lies in its inability to properly retrieve and return values

Within my code, I have a function that looks like this: $.fn.validate.checkValidationName = function(id) { $.post("PHP/submitButtonName.php", {checkValidation: id}, function(data) { if(data.returnValue === true) { name = true; } else { ...

Convert a JavaScript object into a serialized form

Alright, so here's the thing that's been bugging me. I have this JavaScript object that I need to pass to a PHP script using jQuery AJAX. But every time I try to pass it as is, I get an error. It seems like the object needs to be serialized befor ...

Embedding links in v-bind:href

I inserted a dynamic link inside the <header></header> section using the method mentioned here: Vue JS and appending a variable to end of a URL Below are the relevant codes: <tr class="notice-row" v-for="(myCase, id) in case ...

Send the user back to the homepage without the need to refresh the page

When the user clicks "Okay" in my window.prompt, the code below opens a new tab. Is there a way to direct the user to the home page without opening a new tab? if (window.confirm("Do you really want to leave?")) { window.open("./Tutoria ...