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

Consider yourself a module for npm, just like a node

I'm currently working on a Javascript project that has been released as a node module. In some parts of the source code, I have used relative paths to import other files within the project: // <this_module_path>/action/foo.js import execution f ...

Issues encountered with AngularJS directive binding inner content not functioning as expected

I am currently developing a feature toggle directive, which requires a check to be performed in order to display content if the check is successful. I want the directive to replace itself with its content without creating a new child scope (so I'm try ...

Adding miscellaneous PHP scripts

When a user clicks on the sample button, my PHP code gets appended. It works fine, but I want to clean up my process. After some research, I learned that using jQuery AJAX is the way to go. The only problem is, I'm not sure how to implement AJAX. I&ap ...

Integrating individual front end JavaScript files into an Express.js application

I've been working on a JavaScript file that contains over 200 lines of code for the front end logic of my project. It handles interactions like button clicks, image displays, and more, similar to a game. However, I'm struggling to figure out how ...

The width:auto attribute for images in ie6 is not functioning as expected

I am facing a challenge with dynamically changing and resizing an image element to fit its container. My current approach involves: Resetting the image: // Ensuring the 'load' event is re-triggered img.src = ""; // Resetting dimensions img. ...

The InjectionToken component is not exported by AngularFire

I am running into some challenges while trying to develop an Angular-Fire application. I was following a specific tutorial which can be found at: However, when I integrate angular-fire into my application, I encounter an issue where the "server" fails to ...

Master the art of utilizing angular-filter

Encountering some challenges while attempting to utilize angular-filter: The following links have been imported into the HTML file: <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script> <script src=" ...

Mastering advanced authentication with Passport and the JwtStrategy

During a recent project I downloaded from the internet... In one specific part of the code, the following is implemented: passport.use(new JwtStrategy({ secretOrKey: credentials.secret, jwtFromRequest: ExtractJwt.fromAuthHeader(), }, ...

Check for duplicate in AngularJS and replace with larger duplicate

I have this piece of code where I am currently checking for duplicates using the isDuplicate boolean. However, I now want to enhance my code by comparing another property called colorId and then setting the isBigger property for the larger one :) Do you ha ...

Detecting When an Input has an :invalid Selector in Jquery

Here is the code snippet I am currently working with: HTML <input type="text" data-value="1" data-type="input-records" placeholder="Value" pattern="\d{1,4}$" /> CSS input[type=text]:invalid { background-color: red; } Javascript $("[data-ty ...

Display and conceal frequently asked questions using JQuery

I'm currently facing an issue with using JQuery to toggle between showing and hiding content when a user clicks on a specific class element. Here is my HTML code: <div class="faqSectionFirst"> Question? <p class="faqTextFirst" style=' ...

Is it possible for us to perform an addition operation on two or more items that belong to the same

I am faced with a challenge involving 3 objects of the same type, each having different values for their properties. My goal is to add them together as illustrated below: Consider this scenario: objA = { data: { SH: { propertyA: 0, propertyB: ...

What is the smallest server.js file needed to run a react/redux application?

I have successfully configured my project using webpack and babel for ES6 transpilation with the specified presets: { "presets": ["react", "es2015", "stage-1"] } My webpack production configuration is structured as follows: var path = require('pa ...

What could be causing the Angular HTTPClient to make duplicate REST calls in this scenario?

I am encountering an issue with my Angular service that consumes a Rest API. Upon inspecting the network and the backend, I noticed that the API is being called twice every time: Here is a snippet of my Service code: getAllUsers():Observable<any>{ ...

Deliver data in batches of ten when the endpoint is accessed

I am currently in the process of developing a web application using Next.JS and Node. As part of this project, I have created my own API with Node that is being requested by Next.JS. One particular endpoint within my API sends data to the front end as an ...

Tips for correctly linking JS and CSS resources in Node.js/Express

I have a JavaScript file and a stylesheet that I am trying to link in order to use a cipher website that I created. Here is my File Path: website/ (contains app.js/html files and package json) website/public/css (contains CSS files) website/public/scri ...

What is the encoding for Javascript in UTF-8?

My current ajax call is able to successfully send the request and retrieve the expected response. However, I am facing difficulty in correctly displaying it in li items. $.ajax({ url: "{% url 'users:profile_page_tags_get' 'primary&apos ...

Receive a 404 error message while navigating through routes in Laravel

I recently came across an interesting tutorial by David Mosher on integrating Angular JS end-to-end. You can check it out on YouTube: http://www.youtube.com/watch?v=hqAyiqUs93c. However, I encountered a bit of trouble while trying to route the /auth/login ...

React has been reported to display a Minified React error even in its development mode

Currently, I am utilizing browserify and babel for transpiling and bundling my script. However, a challenge arises when React 16 is incorporated as it presents the following error message: Uncaught Error: Minified React error #200; for more details, kin ...

Verify if a certain value exists in an array while using ng-if inside ng-repeat

Currently, I have a loop using ng-repeat that goes through a list of wines obtained from an API. Alongside this, there is an array variable containing all the IDs of wines that have been marked as favorites and retrieved from the database. My goal is to sh ...