Creating a dynamic navigation menu in Angularjs using UI-Bootstrap tabs and UI-Router for seamless user

When working on this Plunker, I encountered an issue with the functionality of menu links and tabs. The problem arises when trying to navigate between 'Route 1' and 'Route 2'. Clicking twice on 'Route 1' doesn't properly return from Route 2 tabs, and clicking twice on the 'Route 2' menu link fails to render the tabs content.

The following snippet of code is where I suspect the problem lies:

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

  $urlRouterProvider.otherwise("/");

  $stateProvider
    .state('route1', {
      url: "/",
      templateUrl: "route1.html"
    })
    .state('DocumentoMasterView', {
      url: "/route2",
      templateUrl: "route2.html",
      controller: 'myAppController'
    })
    .state('DocumentoMasterView.A', {
      url: '/detail',
      templateUrl: 'route2.A.view.html',
      controller: 'myAppController'
    })
    .state('DocumentoMasterView.B', {
      url: '/image',
      templateUrl: 'route2.B.view.html',
      controller: 'myAppController'
    })
    .state('DocumentoMasterView.C', {
      url: '/submenu',
      templateUrl: 'route2.C.view.html',
      controller: 'myAppController'
    })

});

 myapp.controller('myAppController',['$scope','$state',function($scope, $state){
        $scope.tabs = [
           { heading: 'A View', route:'DocumentoMasterView.A', active:true},
           { heading: 'B View', route:'DocumentoMasterView.B', active:false },
           { heading: 'C View', route:'DocumentoMasterView.C', active:false }
        ];

        $scope.go = function(route){
           $state.go(route);
        };

        $scope.active = function(route){
           return $state.is(route);
        };

       $scope.$on('$stateChangeSuccess', function() {            
         $scope.tabs.forEach(function(tab) {
               tab.active = $scope.active(tab.route);
         });
       });

Answer №1

To ensure that example works correctly, I have implemented this change (you can view it here)

There is no need for a state change in this scenario.

   // Remove the following code
   $scope.go = function(route){
       $state.go(route);
   };

   $scope.$on('$stateChangeSuccess', function() {
       $scope.tabs.forEach(function(tab) {
           tab.active = $scope.active(tab.route);
       });
   });

We should handle all tab selections in a different manner.

   // Instead, use this code snippet
   $scope.go = function(t){
       $scope.tabs.forEach(function(tab) {
           tab.active = $scope.active(t.route);
       });
       $state.go(t.route);
   };

You can review the changes here

Furthermore, consider reevaluating the use of

<div ng-controller="myAppController">
with ui-router. While it may work, utilizing states allows you to define all components more efficiently.

To demonstrate this concept, check out this example which illustrates how to achieve similar functionality without ng-controller and using a parent layout state.

Answer №2

Radim provided a helpful answer, but there is a more efficient and modern approach available. ui-router allows for active states to handle CSS and state changes directly from the view, rather than cluttering up your controller with extra logic.

Incorporate the following code into your navigation:

<ul>
  <li ui-sref-active="active" class="item">
    <a href ui-sref="route1">route1</a>
  </li>
</ul>

That's all you need! The currently active state or view will automatically apply the "active" class to the respective list element, based on the specified UI router functionality.

For your specific navigation needs, use this setup:

<ul>
  <li ui-sref-active="active" class="item">
    <a href ui-sref="route1">route1</a>
  </li>
    <li ui-sref-active="active" class="item>
    <a href ui-sref="DocumentoMasterView">DocumentoMasterView</a>
  </li>
    <li ui-sref-active="active" class="item">
    <a href ui-sref="DocumentoMasterView.A">DocumentoMasterView.A</a>
  </li>
    <li ui-sref-active="active" class="item">
    <a href ui-sref="DocumentoMasterView.B">DocumentoMasterView.B</a>
  </li>
    <li ui-sref-active="active" class="item">
    <a href ui-sref="DocumentoMasterView.C">DocumentoMasterView.C</a>
  </li>
</ul>

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

Master the art of using Insertion Sort in javascript with the help of Khan Academy

Seems like I am almost there with solving this problem, but my code isn't running as expected. Can someone offer some feedback and point out where I went wrong? var insert = function(array, rightIndex, value) { for(var j = rightIndex; j & ...

What's the most efficient method of exporting modules along with their submodules in (Vue, React)?

Looking for the most efficient method to export a module that contains submodules with the help of an index.js? I have been following a specific naming and saving convention for my web components in projects involving Vue or React. However, I am interested ...

The CSS class is specifically assigned to a single element

After every two seconds, my JavaScript function is triggered and based on certain logic, I aim to add a CSS class with an effect to an HTML element on the page. var counter = 0; $interval(function () { counter++; ...

underscore.js is throwing an error with the message "unexpected token ILLEGAL

<% var cache_badge = ''; for (var i=0; i<badges.length; i++) { cache_badge += " <a href='' data-toggle='popover' data-content='test' data-original-title='test'><img style='padding-r ...

AngularJS allows for submitting form data to a new window by utilizing the form

At the moment, I have a JavaScript function that sends a form POST request and opens it in a new window. Now, I want to convert this into AngularJS. Here's the current function. The three parameters passed in determine the post URL and some data valu ...

Utilizing a server-side PHP environment alongside a dynamic JQuery slider

I recently completed a PHP course on Codecademy and wanted to dive into a new project to further enhance my skills. However, I've hit a roadblock while working on it - specifically having trouble with the AJAX functionality. I'm struggling to ide ...

Adding HTML content to routes in ExpressOrEnhancing routes

Recently, I've been working with a basic index.html file. My goal is to have the routes file append an HTML button when requested by the browser without actually modifying the original file. This may seem like a peculiar idea, but my intention is to c ...

How can I trigger a page postback in ASP.NET after downloading a file?

Here is my current scenario: The user clicks on a LinkButton, triggering a PostBack on the page. However, I also need to initiate a file download for the user simultaneously. To achieve this, I added the following code to the LinkButton: lnkPrint.Attri ...

Activating/Deactivating Drop-down Menus Depending on Selected Options

I'm attempting to control the enable/disable functionality of two select boxes based on the user's selection in a third box using jQuery. The goal is to enable select box 2 when the user chooses one of the first two options in the controller, and ...

Exceedingly High Outputs from the Haversine Formula

I am currently utilizing the Haversine formula in order to compute the distance between two specific points on the earth's surface. Below is the code snippet I am using: var app = angular.module('app', []); app.controller('firstCtr ...

Error: React Native Component Exception - a potential hiccup in

As a newcomer to React Native, I've encountered an issue while trying to bind data from a local JSON server API. Everything worked fine when I used a class component for my EventList, but after integrating Navigation in App.js and changing it to a fun ...

Combining two objects: A guide for merging with AngularJS or basic JavaScript

There are two sets of data $scope.c= {"Sedan":{"Toyota":["Camry","Corolla"]},"SUV":{"Jeep":["Wrangler"]}}; var d= {"SUV":{"Ford":["Escape"],"Chevrolet":["Tahoe"]}}; After combining the two sets, I expect to see the following outcome {"Sedan":{"Toyota": ...

Executing a jQuery function in vb.net codeBy utilizing vb.net, the jQuery

Encountering an unusual issue where I need to toggle the visibility of a div both server side and client side without being able to change it to a panel. To achieve this, I am currently using the following code to toggle its visibility client side: $(&ap ...

inject custom styles into a Material-UI styled component

Although I have come across similar questions, none seem to directly address my current situation. I am in the process of transitioning from MUI v4 to MUI v5 and have encountered various scenarios where a specific style is applied externally. For instance ...

Is there a way I can link a variable to a URL for an image?

Creating v-chip objects with dynamic variable names and images is causing an issue. The image source string depends on the name provided, but when I bind the name to the source string, the image fails to load. Despite trying solutions from a similar questi ...

When working with React-Native App and combining React-Navigation with Redux, a common error may occur stating that 'action.routeName' is not an object. This issue can be

I encountered an error in my React Native app while implementing react-navigation within redux. The issue, along with a screenshot for reference, can be found here. Currently, I have not incorporated any redirects into the application. However, my plan in ...

Generating variables dynamically within a React Native component

In my React Native component, I need to create a variable that will be used multiple times. Each instance of this component should have a different variable name for reference. <View ref={view => { shapeView = view; }} onLayout={({ nativeE ...

Explain the inner workings of the setTimeout() function in JavaScript

My goal is to create a line in my code by placing points according to the line equation and adding a 100 millisecond delay before each point is displayed. However, when I try to run the code, it seems to wait for some time and then displays all the points ...

Vue-Firebase: A guide to linking multiple Firebase services in a single app

I am facing an issue with connecting to two firebases within the same project. In my project, I have two javascript files that connect to each firebase separately, which seems fine. Here is how I import them: import db from '../FireBase' i ...

How can I transfer information from one page to another in Next.js 14 without displaying the data in the URL?

As a React Native developer working on a web app, I'm facing a challenge with passing data from one page to another in Next.js 14 without displaying the data in the URL. I have a specific app directory within my Next.js project. When I mention not sh ...