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

What causes Firefox's CPU to spike to 100% when a slideshow begins that adjusts the width and left coordinates of certain divs?

Seeking Advice I'm in need of some help with identifying whether the code I'm working on is causing high CPU usage in Firefox or if it's a bug inherent to the browser itself. The situation is getting frustrating, and I've run out of so ...

.ajax() triggers a page refresh upon pressing the ENTER key

Utilizing Ajax to update the database with a new folder leads to page refresh when hitting ENTER. On the form, I have onkeypress="if(event.keyCode==13) savefolder();". Below is the Javascript code where pressing enter calls savefolder function that sen ...

Looping through an object with AngularJS's ng-repeat

Upon receiving an object as the scope, which has the following structure: The controller function is defined as follows: module.controller('ActiveController', ['$scope','$http', function($scope, $http) { $h ...

Creating code in AngularJS

I have the following template structure: <h1 class="text-center" ng-bind-html="row.text"></h1> When the content of my row.text is a string like this: Hi your name is {{ name }} It will display as shown below: Hi your name is {{ name }} ...

Unable to Trigger Virtual Click Event on Calendar in JavaScript

My workplace utilizes a custom web application with a date picker/calendar that I am attempting to modify programmatically. The app is built in Vue, which has added complexity to my task. Despite exhaustive efforts, I have been unable to select or inject d ...

What is the best way to pass a value to a modal and access it within the modal's component in Angular 8?

How can I trigger the quickViewModal to open and send an ID to be read in the modal component? Seeking assistance from anyone who can help. Below is the HTML code where the modal is being called: <div class="icon swipe-to-top" data-toggle="modal" da ...

Method in Vue.js is returning an `{isTrusted: true}` instead of the expected object

I am having an issue with my Vue.js component code. When I try to access the data outside of the 'createNewTask' function, it renders correctly as expected. However, when I attempt to log the data inside the function, it only returns {isTrusted: ...

Error: JQuery's on() function is not defined

After modifying the code in the original and changed code boxes, I'm now encountering an Uncaught Type error: Undefined is not a function. Any thoughts on why this might be happening? Thanks Original: $('.comment').click(function(e){ ...

The Socket IO server fails to broadcast a message to a designated custom room

I am currently working on developing a lobby system that allows players to invite each other using Socket io version 4. The process involves the client sending a request to create and join a room, followed by emitting messages to other clients in the same ...

Organizing AngularJS Data by Initial Letter with the <select></select> HTML Element

I'm trying to figure out how to filter an ng-repeat function based on the first letter of each option. For example, I want to filter a set of array or string so that only options starting with "A" or "B" are displayed. Can anyone help me with this? H ...

Tips for transferring a data table (an object) from a JavaScript file to Node.js

On my HTML page, there is a table displaying student names and information, along with controls to manage the table. I created a save button to save this table as an object named SIT in my JavaScript code. I was able to manually save this table in MongoDB ...

Iterating through a for loop in Angular2 to send multiple GET requests to a Django backend

Currently, I'm facing a challenge with performing multiple GET requests using Angular2 within a Django/Python environment. After successfully making an API request and retrieving a list of users to determine the current user's ID, I utilize a .f ...

What is Angular's approach to managing the @ symbol in view paths?

I found some interesting data lake sources on AWS. I came across their package.js file, which includes the following code: '@package': { templateUrl: 'package/package.html', controller: 'PackageCtrl' } I am curious a ...

The accuracy of real-time visitor numbers in Google Analytics is often unreliable

My website uses Google Analytics to track the page chat.php. The code snippet is correctly placed on the page according to the documentation. Within this page, there is a Flash object that connects users to an IRC chat room. Currently, there are 50 unique ...

I'm looking for a solution to pass a PHP object as a parameter in JavaScript within an HTML environment,

I am currently working on a project using Laravel 5. I have a table in my view, and I want to pass all the data values to a JavaScript function when a link is clicked. I have tried several methods but have been unsuccessful so far. @foreach ($basl_offic ...

Implementing Conditional ng-src Loading based on a Given Value

I have a dropdown menu that contains a list of image names. When an image is selected, it should be loaded and displayed using the ng-src directive. Everything works perfectly fine when a name is chosen. The issue arises when the dropdown menu also includ ...

TinyMCE - Utilizing selection.setContent along with getContent for the Warp Button

I am looking to implement a button that will wrap content with all tags. Snippet of Code: editor.addButton('MobileToggleArea', { text: '<M>', icon: false, onclick: function (){ editor.selection. ...

URLs embedded in a JSON string

Currently, I am using an angular template to display JSON data in a calendar format showing various events. I am wondering if it's possible to include URL links within a string in the JSON data. Here is an example: { "name" : "Lee Morgan", ...

Using the input method in JavaScript cannot extract an object property

Recently, I have been working with this JavaScript code provided below. It is essential for me to retrieve the votecount for a game based on user input. function Game(gamename,votes) { this.gamename = gamename; this.votes = votes; }; var lol = ne ...

Creating a C# view model with jQuery integration

I am facing an issue with binding a list property of a view model using jQuery. The view model in question is as follows: public class ToolsAddViewModel { public string Tools_Name { get; set; } public string Tools_Desc { get; set; } ...