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

Is there a return value for the GEvent.addListener(...) function?

I have a question regarding GEvent.addListener(map, "click" function(){...}). I couldn't find any information about what it returns in the callback function in the GMaps reference. Can you provide some insight on this? The documentation mentions two p ...

JavaScript does not support the enumeration of programs

I'm currently working on a program that takes user input (library, authorName) and displays the titles of books written by the author. Here is an example library structure: let library = [ { author: 'Bill Gates', title: 'The Road Ah ...

Issue with Discord.js: Newly joined user's username appears as undefined

robot.on('guildmateEntry', person =>{ const greeting = new Discord.MessageEmbed() .setTitle(`Greetings to the realm, ${individual}!`) const room = person.guild.channels.cache.find(channel => channel.name === " ...

When attempting to upload a file using ajax, the $_FILES variable in PHP came

I am facing an issue with uploading images via AJAX where my PHP is not receiving the AJAX post. function handleFileSelect(evt) { files = evt.target.files; // FileList object $('.thumb-canvas' + filesId).css('display','bl ...

Update the Ngrx reducer when the component is present on the page

One dilemma I am facing involves managing two components within a page - an update user form and a history of events. Each component has its own reducer (user and events). My goal is to update the list of events in the store through an API call once the us ...

The average duration for each API request is consistently recorded at 21 seconds

It's taking 21 seconds per request for snippet.json and images, causing my widget to load in 42 seconds consistently. That just doesn't seem right. Check out this code snippet below: <script type="text/javascript"> function fetchJSONFil ...

Trigger the fire event on .click() except when text is being selected

I am currently working on a chat box project and I want the input field within the message area to automatically get focused when the user clicks anywhere in the chat box. However, I don't want this functionality to interfere with text selection for c ...

Learn how to move to a new line when inputting data into a CSV file with JavaScript

My challenge involves taking an array of objects, for example: array=[hello, how, are, you], extracted from the document.innerHTML. I aim to write these objects to a CSV file using puppeteer and JavaScript, each on a new line. Although when using the sta ...

Preserving the "height" declaration in jQuery post-Ajax request (adjusting height after dropdown selection loads product information, resetting heights of other page elements)

Looking for a way to set a height on product descriptions using jQuery? Check out the solution below: https://www.example.com/product-example Here is the code snippet that can help you achieve this feature: $(document).ready(function() { var $dscr = $ ...

Save the file to a specific folder and compress the entire folder into a

I have encountered an issue while attempting to write a file to a directory named templates and then stream a zip file with the content that was just written. The problem arises when the zip file is returned, displaying an error message "Failed - Network E ...

"Execute this function when the scope is either the last one or when it is considered to be empty

In the realm of custom directives, I have crafted a special one: .directive('repeatDone', function() { return function(scope, element, attrs) { if (scope.$last) { scope.$eval(attrs.repeatDone); } } }) This directive serves a d ...

Updating HTML content using jQuery by iterating through an array

When I write the following HTML code: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <h1 id="message"> </h1> and include the corresponding JavaScript code: messages = ["Here", "are", ...

Effectively controlling two distinct Azure resources within one domain name through domain routing

I am currently in the process of deploying a React application on Microsoft Azure that includes a basic content management feature. Essentially, when users visit the website and access static content, the app retrieves HTML code from a database and display ...

Creating a new file for a promise function

Initially, I managed to make this function work within a single file. However, I prefer organizing my code by splitting it into multiple files. // library.js file module.exports = { get: () =>{ return new Promise((reject, resolve) =>{ ...

What is the simplest way to extract only the error message?

Having this code snippet. $('div#create_result').text(XMLHttpRequest.responseText); If we look at the content of XMLHttpRequest, it shows: responseText: Content-Type: application/json; charset=utf-8 {"error" : "User sdf doesn't exist"} st ...

Implement a one-second delay before nesting another animation

I'm currently utilizing a timeout function, but I am interested in using a delay instead. My goal is to have the second animation start when one second has passed from the beginning of the first animation, and it should be a linear animation. How can ...

The deployment on heroku encountered an error during the build process

I'm attempting to deploy my React application on Heroku, but I keep encountering the following errors: -----> Installing dependencies Installing node modules npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ...

The amazingly efficient Chrome quick find feature, accessible by pressing the powerful combination of Ctrl + F, ingeniously

Currently using Google Chrome version 29.0.1547.62 m. I've employed the CSS attribute overflow set to hidden on the parent element, which renders some of my DIV elements hidden from view. Additionally, these concealed DIV elements are adjusted in pos ...

No data found in php://input when accessing Azure

Having an issue with posting a complex JSON object to my Azure IIS server running PHP 5.4 using AngularJS: var request = $http({ method: "post", url: "/php/mail.php", data: $scope.contactForm, headers: { 'Content-Type': & ...

The confirmation dialogue is malfunctioning

Need some assistance with my code. I have a table where data can be deleted, but there's an issue with the dialog box that pops up when trying to delete an item. Even if I press cancel, it still deletes the item. Here is the relevant code snippet: ec ...