Avoid triggering child states in ui-router

Here is the progress I have made with ui-router states:

$stateProvider
  .state('tools', {
    url: '/tools/:tool',
    template: '<div ui-view=""></div>',
    abstract: true,
    onEnter: function ($stateParams, $state, TOOL_TYPES) {
      if (TOOL_TYPES.indexOf($stateParams.tool) === -1) {
        $state.go('error');
      }
    }
  })
  .state('tools.list', {
    url: '',
    templateUrl: 'app/tools/tools.tpl.html',
    controller: 'ToolsController'
  })
  .state('tools.view', {
    url: '/:id/view',
    templateUrl: 'app/tools/partials/tool.tpl.html',
    controller: 'ToolController'
  });

The parent state requires parameter tool, which must be included in the TOOL_TYPES array. If not available, the user will be redirected to the error page.

Although everything functions correctly, I am encountering two errors:

TypeError: Cannot read property '@' of null

TypeError: Cannot read property '@tools' of null

It seems that the child states are being triggered regardless. Is there a way to prevent this or achieve my desired outcome differently?

Answer №1

The documentation for Angular ui-router explains that the onEnter callbacks are triggered when a state becomes active, thereby activating child states as well.

To address this issue, it is necessary to implement two key steps:

  1. Create a resolve function that returns a rejected promise if a specific condition does not match the state requirements. Ensure that the rejected promise includes information about the state to redirect to.

  2. Develop a $stateChangeError event handler within the $rootScope and utilize the 6th parameter which represents the information passed in the rejected promise. Use this information to create the redirection functionality.

See Demo Here

Javascript

angular.module('app', ['ui.router'])

  .value('TOOL_TYPES', [
    'tool1', 'tool2', 'tool3'
  ])

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

    $stateProvider

      .state('error', {
        url: '/error',
        template: 'Error!'
      })

      .state('tools', {
        url: '/tools/:tool',
        abstract: true,
        template: '<ui-view></ui-view>',
        resolve: {
          tool_type: function($state, $q, $stateParams, TOOL_TYPES) {

            var index = TOOL_TYPES.indexOf($stateParams.tool);

            if(index === -1) {
              return $q.reject({
                state: 'error'
              });
            }

            return TOOL_TYPES[index];
          }
        }
      })

      .state('tools.list', {
        url: '',
        template: 'List of Tools',
        controller: 'ToolsController'
      })
      .state('tools.view', {
        url: '/:id/view',
        template: 'Tool View',
        controller: 'ToolController'
      });

  })

  .run(function($rootScope, $state) {
    $rootScope.$on('$stateChangeError', function(
      event, toState, toStateParams, 
      fromState, fromStateParams, error) {

        if(error && error.state) {
          $state.go(error.state, error.params, error.options);
        }

    });
  })

  .controller('ToolsController', function() {})
  .controller('ToolController', function() {});

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

Retrieve the minimum and maximum values from a multi-dimensional array

If my array consists of the following subarrays: array = [[1, 5, 8, 9], [3, 7], [3, 8, 33], [2], [0, 6]] I am looking to determine the maximum and minimum values in this array. For example, in this case: max = 33, min = 0 While I have come across exampl ...

Implement a callback function in React using hooks after changing the state

Back in the days of React before hooks, setting state and calling a function after it had been set was achieved using the following syntax: this.setState({}, () => {//Callback}) Now, with hooks, what is the equivalent way to achieve this? I attempted ...

javascript Unable to execute function in Internet Explorer 11

I'm experiencing an issue where this script works in Google Chrome but not in IE 11. Can anyone explain why?: <script type="text/javascript"> window.onload = function () { var ammount = document.getElementById('ammount'); var price = ...

Unable to extract a particular value from a JSON data structure

This situation has been on my mind for a good couple of hours now. I have this json object with example values like so: { "events": [ { "id": 64714, "live": false, "start": "1399117500", "league_ ...

Tips on incorporating personalized javascript functions into Durandal

I am currently working on my first project using the Durandal framework to create a basic website. I have encountered an issue while trying to incorporate a simple JavaScript function. My goal is to execute the function after the DOM has loaded, but I am u ...

obtain data from JSON using JavaScript

Greetings! I am dealing with a JSON output that looks like this: "{ \"max_output_watts\": 150, \"frame_length_inches\": \"62.20\", \"frame_width_inches\": \"31.81\" }" I am using it in a functi ...

Utilize the Webstorm debugger in conjunction with node.js for seamless debugging

Several weeks ago, I attempted to get the webstorm debugger up and running, but unfortunately, it didn't work. Now, I'm giving it another shot, but I'm faced with the same outcome. I am following the instructions outlined here: http://www.j ...

What is the best way to reorganize the switch case in order to invoke methods from a class?

I have a special character called Hero within my game, this Hero inherits characteristics from the Player class and can perform a variety of actions. The majority of these actions are customized to suit the Hero's abilities. class Hero extends Player ...

Is there a way to create a Captcha image from text using JavaScript in an HTML document?

As I work on creating a registration web page, ensuring security is key. That's why I'm looking for a way to generate captcha images for added protection. Any suggestions on how I can transform text into captcha images? ...

Having trouble accessing the scrollHeight property of null when using Selenium WebDriver

I am currently working on a function in my code that is responsible for scrolling the page. This particular function was inspired by code used to scrape Google Jobs, which can be found here. However, I encountered an error that reads "javascript error: Ca ...

Automatically compile files while performing an npm install or update

I am looking for a way to automatically compile my TypeScript code into JavaScript when another project requires it. For example, when a project runs npm install or updates with my project as a dependency, I want a specific command to be executed after all ...

Stop user from navigating to specific route using React-router

I am currently utilizing react-router with history useQueries(createHashHistory)(), and I have a requirement to restrict navigation to certain routes based on the route's configuration. The route configuration looks like this: <Route path="/" name ...

Can VueJS Computed handle multiple filters at once?

I am encountering an issue with this code - when I attempt to add another filter inside the computed section, it doesn't work. However, if I remove the additional filter, the code functions correctly. My goal is to have both company and product searc ...

The 'npm start' command is failing to recognize the changes made to the

I am embarking on a new node application journey, starting with the package.json below, which is quite basic. { "name": "mynewnodeventure", "version": "1.0.1", "description": "Exploring node", "main": "index.js", "start": "node server. ...

Can you provide the keycodes for the numpad keys: "/" and "." specifically for the libraries I am utilizing or any other library that does not overlook them?

I've hit a roadblock with my Chrome Extension development. Despite using two different methods to add keyboard functionality, the keys "/" for divide and "." for decimal on the keypad are just not registering. I've attempted to tackle this issue ...

Different types of video formats used for html5 video players

Looking for some guidance here. I'm currently in the process of developing a website that allows users to upload their own videos. For the video player, I've opted for the HTML5 player by . My main concern is ensuring that the HTML5 player can on ...

"Unlocking the Power of jQuery: A Guide to Accessing XML Child

I'm struggling to extract the xml in its current format. While I can easily retrieve the InventoryResponse, I am facing difficulties when trying to access the child node a:Cost. Despite conducting research, I have been unable to find a solution that w ...

How to resolve CORS error when using custom request header in Django with JavaScript and redirecting to OPTIONS request?

I am currently working on building an API library using Django. This API will be accessed by javascript, with the Django-API and javascript running on separate servers. The Django API library requires a custom request header from the javascript front end, ...

Having trouble getting the toggle button JavaScript code to function properly in React JS?

I'm in need of some assistance with the comment section located below the JavaScript Code. I am trying to implement a toggle button / hamburger button, but it seems that addEventListener is not necessary for ReactJS. Can someone provide guidance on wh ...

What is preventing me from being able to effectively transmit the array using the POST method in Express?

As a newcomer trying to learn Express, I believe I am on the right path, but I am currently facing some challenges with the POST method. The issue I'm encountering is as follows: Whenever I send a POST request to an HTTP file, I receive an empty ob ...