Change the controller's classes and update the view in Angular

In my angular application, I have a popup window containing several tabs. These tabs are styled like Bootstrap and need to be switched using Angular. The code for the tabs is as follows (simplified):

<div class="settingsPopupWindow">
    <div>                   
        <!-- Nav tabs -->
        <ul class="nav nav-tabs">
            <li class="{{getStyle(0)}}" ng-click="showTab(0)">
                <a href="">
                    First tab navigation
                </a>
            </li>
            <li class="{{getStyle(1)}}" ng-click="showTab(1)">
                <a href="">
                    Second tab navigation
                </a>
            </li>                                       
        </ul>

        <!-- Tab content-->
        <div class="tab-content">
            <div class="tab-pane {{getStyle(0)}}">                          
                First tab content
            </div>

            <div class="tab-pane {{getStyle(1)}}">
                Second tab content
            </div>                                      
        </div>
    </div>

The controller code for switching tabs looks like this:

.......
$scope.active = 0;     

$scope.showTab = function (tabNumber) {
    $scope.active = tabNumber;
};

$scope.getStyle = function(n) {
    if (n === $scope.active) {
        return 'active';
    }
    else {
        return '';
    }
}
.......

Both navigation elements and tab blocks should have an active class when selected.

Initially, everything works correctly: the first tab is active with the First tab navigation highlighted and its content displayed. However, clicking on the Second tab navigation only activates the navigation element without displaying the corresponding content.

Even though the second tab's navigation appears active, the content of the first tab remains visible in the panel. This results in needing to click twice on the Second tab navigation to switch to the second tab successfully.

If I first select the Second tab navigation and then the First tab navigation, the First tab navigation becomes active but shows the content of the second tab in the panel. It seems like there is a delay between switching the navigation elements and tab panels, despite both being controlled by the same function.

I would appreciate some assistance in resolving this issue. Thank you.

Update

I attempted to use ng-class instead of class, but it did not solve the problem. There still exists a one-click delay between switching the navigation elements and tab panels. While the showTab() function operates correctly in updating the active tab number, the styles of the tabs do not update immediately after changing the active tab. This inconsistency persists whether using class or ng-class.

Answer №1

If you want to dynamically set CSS classes on an HTML element, consider using the ngClass attribute.

As mentioned in the ngClass documentation -

The ngClass directive allows for the dynamic assignment of CSS classes by binding an expression that defines all classes to be applied.

In my perspective, it is advisable not to use a function to determine the class name,
but rather utilize the ng-class with the tag's scope property:

<div class="tab-pane" ng-class="{'desiredClassName': tagObject.isTagActive}">                          
    Content for the first tab
</div>
<div class="tab-pane" ng-class="{'desiredClassName': tagObject.isTagActive}">
    Content for the second tab
</div>

This approach allows tagObject to hold the tag's information.
If it belongs to a collection, you can utilize the ng-repeat attribute.

The isTagActive property can be updated through any method (such as scope or service).
Angular will then promptly apply the desired classes to the tag's <div>.

Answer №2

To implement tab navigation, utilize the ngClass directive.

For the tab navigation section:

<li ng-class="{'active': active == 0}" ng-click="ShowTab(0)"><a href="">First tab nav</a></li>
<li ng-class="{'active': active == 1}"  ng-click="ShowTab(1)"><a href="">Second tab nav</a></li>

And for the tab content section:

<div class="tab-pane" ng-class="{'active': active == 0}">                          
    First tab content
</div>
<div class="tab-pane" ng-class="{'active': active == 1}">
    Second tab content
</div>  


EDIT: Functional Example

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
  $scope.active = 0;

  $scope.showTab = function(tabNumber) {
    $scope.active = tabNumber;
  };
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <!-- Navigation tabs-->
  <ul class="nav nav-tabs">
    <li ng-class="{'active': active == 0}" ng-click="showTab(0)">
      <a href="#">First tab navigation</a>
    </li>
    <li ng-class="{'active': active == 1}" ng-click="showTab(1)">
      <a href="#">Second tab navigation</a>
    </li>
  </ul>

  <!-- Content panes -->
  <div class="tab-content">
    <div class="tab-pane" ng-class="{'active': active == 0}">
      First tab content
    </div>

    <div class="tab-pane" ng-class="{'active': active == 1}">
      Second tab content
    </div>
  </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

The onKeyUp event in Material-UI components does not seem to be functioning as

I am experiencing an issue with a material-ui component Grid where the onKeyUp event does not seem to be triggering as expected. Here is the code snippet: <Grid item xs={12} onKeyUp={handleClickOnKeyUp} sx={{cursor: "pointer"}} onClick= {ha ...

Trouble with the div element's change event

Hey there! I'm having trouble with this jQuery code that is supposed to fade in or fade out a div based on its contents. Here is the HTML code: <div class="mainContentWrapper"> sample text </div> And here is the CSS code: div.main ...

The issue with the jQuery function lies in its inability to properly retrieve and return values

Within my code, I have a function that looks like this: $.fn.validate.checkValidationName = function(id) { $.post("PHP/submitButtonName.php", {checkValidation: id}, function(data) { if(data.returnValue === true) { name = true; } else { ...

Tips for effectively highlighting search text within HTML content without causing any issues

I am in search of a solution that can assist me in searching for specific terms within an HTML string while also highlighting them. I have the ability to remove the HTML content from the string, but this poses the problem of losing the context of the origi ...

javascript unusual comparison between strings

I am working on an ajax function that is responsible for sending emails and receiving responses from the server in a JSON format with type being either success or error. $("#submit_btn").click(function(event) { event.preventDefault(); var post_d ...

Modify the CSS using JavaScript after a brief delay

I'm creating a homepage that includes animations. Inside a div, I initially have display: none, but I want it to change to display: block after a few seconds. I've been trying to use JavaScript for this purpose, but I'm struggling to find th ...

Can an entire application built with a combination of PHP, JavaScript, and HTML be successfully converted to Angular 7?

After creating a complex application that heavily relies on JavaScript, PHP, HTML, and numerous AJAX calls, I am considering migrating the entire codebase to Angular 7. Is it feasible to achieve this transition without requiring a complete rewrite in Ang ...

Retrieve information from an SQL database using user input in a Classic ASP form without the need to refresh the page

Currently, I am in the process of incorporating a new function into an existing Classic ASP system. This feature involves allowing users to scan a barcode that will automatically populate a text field within a form inside a bootstrap modal. The scanner has ...

Combining numerous objects into one object within an array, each with distinct keys, and displaying them using FlatList

I'm struggling to present this information in a FlatList. Array [ Object { "-N1gqvHXUi2LLGdtIumv": Object { "Message": "Aeaaeaea", "Message_CreatedAt": 1652167522975, "Message_by_Ema ...

Angular 6: Issue TS2339 - The attribute 'value' is not recognized on the 'HTMLElement' type

I have a textarea on my website that allows users to submit comments. I want to automatically capture the date and time when the comment is submitted, and then save it in a JSON format along with the added comment: After a comment is submitted, I would li ...

Creating responsive HTML page text and table with the use of JavaScript

Trying to create a responsive webpage has been a bit challenging. I experimented with height,style.height, style.OffsetHeight, etc. but still struggling to dynamically make a square table. Although the code below changes the height, the table's width ...

An error has been noticed: "Unexpected token o" - Syntax is not

I'm currently developing a web application and have encountered an issue: $("#post").click(function () { var u = $('#u').val(); var j = $('#j').val(); $.post("http://www.myweb.php", { u: u, j: ...

Alert: '[Vue warning]: Directive "in testing" could not be resolved.'

Currently, I am running unit tests within a Vue 2.0 application using PhantomJS, Karma, Mocha and Chai. Although the tests are passing successfully, I am encountering a warning message with each test indicating an issue like this: ERROR: '[Vue warn ...

Using Try and Catch effectively - tips and strategies

As I delve into learning JavaScript on my own, one topic that caught my attention is the try/catch structure. The tutorial I came across only covers how to implement it, but lacks in explaining its practical applications. Is there anyone who can shed som ...

What is the best method for breaking down this JSON data into distinct 'objects'?

I am struggling with deserializing JSON data into multiple instances of an object I have defined. Here is how the object is structured: function Question_Value__c () { this.Id=null; this.Name=null; this.Question__c=null; this.Order__c=null ...

Firebase User Becomes Undefined Upon Refreshing the Web Page

My situation is quite straightforward. I have developed a Firebase web application and I am logging in with my Google account. The problem arises when I have to keep logging back in every time the page is refreshed, as depicted in these steps: Initialize ...

The terser-webpack-plugin and uglifyjs-webpack-plugin are both powerful tools for optimizing

WebPack 4 now utilizes the terser-webpack-plugin in production mode or when the -p argument is specified, which essentially means including --optimize-minimize --define process.env.NODE_ENV="production". This plugin is responsible for minimizing ...

Create a soft focus on the background sans any filters

I am in the process of developing a website and have implemented code to blur out the background: CSS #background{ background: url(img/bg.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o ...

A guide on integrating the MUI Timepicker with the newest 6 version using Formik

I am currently experimenting with the MUI React Timepicker component and facing an issue during integration with Formik for validation. The problem lies in the inability to bind values properly in the initialValues of the form. const [initialValues, setI ...

Disabling the authentication prompt in the browser

Apologies for the repetition, but I would like to pose a more general question. Is there any method on the client side of a web application to predict if requesting a resource will result in a 401 status code and trigger an unattractive authentication pro ...