Navigating through different tabs in an AngularJS application is made simple and efficient with the help of $

I used the angular-authentication-example to create a login page for my project.

After logging in, the homepage should display multiple tabs just like in this example on Plunker.

<ul class="nav nav-tabs" ng-controller="TabsCtrl">
  <li ng-class="tabClass(tab)" ng-repeat="tab in tabs" tab="tab"><a href="{{tab.link}}" ng-click="setSelectedTab(tab)">{{tab.label}}</a></li>
</ul>

However, I am encountering an issue where the multi-tab feature is not integrating properly as a Single Page Application. In the demo, the tabs are supposed to be included within the same view but when I implemented it, each tab takes me to a separate HTML page instead of staying within the main view. I prefer using AngularJS route provider over state provider because the authentication logic in the angular-authentication-example is solid and I don't want to overhaul the entire system.

Answer №1

Latest Update:

Version 1 (No Routing) Check out the Plunker Demo

If you are using the #/jobs syntax, it will redirect to a new view. Here is a complete working solution without routes:

Your code on plunker works because ngRoute was not included in your code.

View the demo on plunker

app.js

$scope.tabs = [
  { id : 'jobs', label : 'Jobs', templateUrl:'jobs-partial.html' },
  { id : 'invoices', label : 'Invoices',templateUrl: 'invoices-partial.html' },
  { id : 'payments', label : 'Payments',templateUrl: 'payments-partial.html' }
]; 

$scope.activeTab = $scope.tabs[0];    
$scope.changeActiveTab = function (tab) {
     $scope.activeTab = tab;
  };

$scope.isActiveTab = function (tabId) {
     return tabId === $scope.activeTab;
  }

Within index.html

<body ng-controller="TabsCtrl">
<ul class="nav nav-tabs" >
  <li ng-class="{active: isActiveTab(tab.id)}" ng-repeat="tab in tabs">
            <a href="" ng-click="changeActiveTab(tab.id)" data-toggle="tab">{{tab.label}} </a>
          </li>
</ul>

<div class="tab-content">
      <div class="tab-pane fade" ng-class="{'in active': isActiveTab(tab.id)}" ng-repeat="tab in tabs"
           ng-include="tab.templateUrl">
      </div>
    </div>
 </body>

Version 2 (With Routing) See the Plunker Demo Here

index.html

<!DOCTYPE html>
<html ng-app="plunkerApp">
<head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">
<script src="https://code.angularjs.org/1.4.8/angular.js"></script>
<script src="https://code.angularjs.org/1.4.8/angular-route.js"></script>
<script src="app.js"></script>
  </head>  
  <body>
    <div ng-view></div>
</body>
  </html>

app.js

angular
  .module('untitled4App', [
    'ngRoute'
  ])
  .config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
    $routeProvider.when('/jobs', {
      templateUrl: '/views/jobs-partial.html',
      controller: 'JobsCtrl'
    }).when('/invoices', {
      templateUrl: '/views/invoices-partial.html',
      controller: 'InvoicesCtrl'
    }).when('/payments', {
      templateUrl: '/views/payments-partial.html',
      controller: 'PaymentsCtrl'
    });

    // making this demo work in plunker
    $locationProvider.html5Mode(false);
  }])
  .factory('tabsService', function () {
    return {
      tabs: function () {
        return [
          {id: 'jobs', label: 'Jobs'},
          {id: 'invoices', label: 'Invoices'},
          {id: 'payments', label: 'Payments'}
        ]
      },
      activeTab: '',
      isActiveTab: function (tabId) {
        return tabId === this.activeTab;
      }
    }
  })
  .controller('JobsCtrl', ['$scope', 'tabsService', function ($scope, tabsService) {
    $scope.tabs = tabsService.tabs();
    $scope.tabsService = tabsService;

    tabsService.activeTab = $scope.tabs[0].id;

  }])
  .controller('InvoicesCtrl', ['$scope', 'tabsService', function ($scope, tabsService) {
    $scope.tabs = tabsService.tabs();
    $scope.tabsService = tabsService;

    tabsService.activeTab = $scope.tabs[1].id;

  }])
  .controller('PaymentsCtrl', ['$scope', 'tabsService', function ($scope, tabsService) {
    $scope.tabs = tabsService.tabs();
    $scope.tabsService = tabsService;

    tabsService.activeTab = $scope.tabs[2].id;
  }]);

jobs.partial.html

<ul class="nav nav-tabs">
  <li ng-class="{active: tabsService.isActiveTab(tab.id)}" ng-repeat="tab in tabs">
    <a href="#/{{tab.id}}">{{tab.label}} </a>
  </li>
</ul>
<div class="tab-content">
  <div class="tab-pane fade in active">
    Jobs
  </div>
</div>

invoices-partial.html

<ul class="nav nav-tabs">
  <li ng-class="{active: tabsService.isActiveTab(tab.id)}" ng-repeat="tab in tabs">
    <a href="#/{{tab.id}}">{{tab.label}} </a>
  </li>
</ul>
<div class="tab-content">
  <div class="tab-pane fade in active">
    Invoices
  </div>
</div>

payments-partial.html

<ul class="nav nav-tabs">
  <li ng-class="{active: tabsService.isActiveTab(tab.id)}" ng-repeat="tab in tabs">
    <a href="#/{{tab.id}}">{{tab.label}} </a>
  </li>
</ul>
<div class="tab-content">
  <div class="tab-pane fade in active">
    Payments
  </div>
</div>

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

Building the logic context using NodeJS, SocketIO, and Express for development

Exploring the world of Express and SocketIO has been quite an eye-opener for me. It's surprising how most examples you come across simply involve transmitting a "Hello" directly from app.js. However, reality is far more complex than that. I've hi ...

What is the best way to execute an API function call within an ng-repeat loop?

I'm encountering an issue with a scope function in my controller that calls an API to retrieve data from a database. This scope function is being used within an ng-repeat loop. However, when I try running the application, it becomes unresponsive. Whil ...

Passing a Ruby session variable to a JavaScript tag: a step-by-step guide

I'm currently collaborating with a vendor who utilizes a JavaScript tag for sale attribution, and I need to pass session variables to the tag. The tag appears to be firing properly, as I can see the variables in the logs, but they aren't reflecte ...

issue arising from integrating material-ui components with code in a react javascript application

Struggling with integrating code and material-ui components in react jsx, I encountered an issue. Here's the problematic snippet: const icols = 0; const makeTableRow = ( x, i, formColumns, handleRemove, handleSelect) => <TableRow key ...

What is the best way to organize JSON files data in a specific sequence?

I successfully converted 3 JSON files into an HTML page using AngularJS. Here is the code I used: Factory code app.factory('myapp', ['$http', function($http) { function getLists() { var tab = ['url1', 'url2 ...

Enhancing websites with font-awesome icons and upgrading from older versions to the latest

Seeking guidance on updating our project to use the latest Macadmine theme. The transition from Font Awesome 3 to Font Awesome 4 requires changing all icons to their proper names. I came across a helpful resource at https://github.com/FortAwesome/Font-Aw ...

Slate Map by Google Navigation

I have a situation here that is similar to the grey maps, except all the buttons are visible. Everything appears normal except for the Map tiles, which are all grey! It's strange because it loads nicely at zoom level 8 and then zooms in to the maximum ...

Is there a way to dynamically adjust @keyframes properties through JavaScript?

I am looking to dynamically change the top value of the keyframes based on a JavaScript variable x. While I have experience changing CSS with JavaScript, this particular challenge has me stumped. Code: var x = Math.floor((Math.random() * 1080) + 1); ...

Tips for creating responsive elements with a z-index of 1 in CSS

I have implemented the code provided in a codepen tutorial, but I replaced the world map image with a USA map. However, the dots are not responsive due to the z-index=1 specified on them. I experimented with vh, vw, and percentages, yet when I resize my s ...

The event listener for the custom cursor in Nuxt.js is failing to work properly when the route

I am currently in the process of constructing a new website for our studio, but am encountering difficulties with getting the custom cursor to function correctly. I implemented a custom cursor using gsap, and it worked perfectly; however, once I navigate t ...

Ionic 2: Image source not being updated

When working with Ionic 2, I encountered an issue where the src attribute of an <img> element was not updating inside the callback function of a plugin. Here is the template code: <img [src]="avatar_path" id="myimg" /> After using the Came ...

Encountered a 'Topology is closed' error while using EJS

After creating my profile.ejs page, I encountered an error upon reloading the page. Can someone help me understand what's causing this issue? Below is all the code I've used. My setup includes Node.js and Express as the server technologies. I cam ...

Auto-complete feature not populating the input field in Google Chrome

Within my register form, I have various INPUT tags present. One of these INPUTs has the name email. <input type=text name=email id=email> When filling out this form in Chrome, I encounter a peculiar behavior. Upon clicking on the email input field ...

Selenium WebDriver keeps crashing with a newSession error after around 70 seconds of running

Recently, a perplexing error surfaced in my previously functional project without any changes to the code. The sudden appearance of this issue may be attributed to a FireFox update or a dependency failure. To help troubleshoot the abrupt cessation, I added ...

Ensure AngularJS ng-show and ng-hide are more secure

When using AngularJS, my goal is to conceal an element so that only authenticated users can access it. Although the ng-hide directive works, there is a vulnerability where someone could modify the class assigned to the element (ng-hide) using Developer To ...

Is $timeout considered a questionable hack in Angular.js development practices?

Here's a question for you: I recently encountered a situation where I needed to edit the DOM on a Leaflet Map in order to manipulate the appearance of the legend. To workaround an issue where the map wasn't generating fast enough to access the n ...

I could really use some assistance with the concept of "AJAX" - can anyone help

After spending several months working with AJAX, I have come to understand the typical request lifecycle: Sending parameters to a background page (PHP/ASP/HTML/TXT/XML ... what other options are available?) Performing server-side processing Receiv ...

Anticipate that the function parameter will correspond to a key within an object containing variable properties

As I develop a multi-language application, my goal is to create a strict and simple typing system. The code that I am currently using is as follows: //=== Inside my Hook: ===// interface ITranslation { [key:string]:[string, string] } const useTranslato ...

Angular code is failing to send a signal to the server following a $http.post request

I've been using angular for about a week now and I've been struggling to solve this issue. I have a service that wraps around $http because multiple controllers make calls to the same URL. On one particular page, there is a lot of server-side bus ...

Recursive function in JavaScript with error handling using try-catch block

Within my nodejs script, I have implemented a system to generate dynamic tables and views based on the temperature data recorded for the day. On some occasions, the creation of these tables is hindered if the temperature falls outside of the normal range ...