Issue with AngularJS: Dynamically generated tab does not become active or selected

Exploring an AngularJS code snippet that generates tabs upon clicking the new button. However, there's an issue where the newly created tab doesn't become active or selected automatically after creation. It seems like the one before the last tab always remains active. Any insights on what might be causing this glitch?

Check out the live example on plnkr: https://plnkr.co/edit/1329tgGonObRQ6Drk75A?p=preview

HTML Code:

<!doctype html>
<html ng-app="plunker">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-animate.js"></script>
      <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-1.2.5.js"></script>
    <script src="example.js"></script>
         <link href="//netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">



  </head>
  <body>

<div ng-controller="TabsParentController">


   <script type="text/ng-template" id="myModalContent.html">
        <div class="modal-header">
            <h3 class="modal-title">I'm a modal!</h3>
        </div>
        <div class="modal-body">
            <ul>
               Sure to delete?
            </ul>
            Selected: <b>{{ selected.item }}</b>
        </div>
        <div class="modal-footer">
            <button class="btn btn-primary" type="button" ng-click="ok()">OK</button>
            <button class="btn btn-warning" type="button" ng-click="cancel()">Cancel</button>
        </div>
    </script>


    <uib-tabset active="active">

        <uib-tab ng-repeat="workspace in workspaces"
             heading="{{workspace.name}}"
             >
            <div ng-controller="TabsChildController">
                <div>
                    {{$parent.workspace.id}} : {{ $parent.workspace.name}}
                </div>
                <input type="text" ng-model="workspace.name"/>
                 <button class="btn" type="button" ng-click="open('sm',workspace)">Delete</button>
            </div>     
        </uib-tab>
      <uib-tab index="0" select="addWorkspace()">
              <uib-tab-heading>
                <i class="glyphicon glyphicon-plus"></i>
            </uib-tab-heading>
        </uib-tab>
    </uib-tabset>
</div>
  </body>
</html>

Javascript Section:

var app = angular.module('plunker', ['ngAnimate','ui.bootstrap']);

app.controller("TabsParentController", function ($scope,$uibModal) {
  $scope.animationsEnabled = true;

  $scope.open = function (size, workspace) {

    var modalInstance = $uibModal.open({
      animation: $scope.animationsEnabled,
      templateUrl: 'myModalContent.html',
      controller: 'ModalInstanceCtrl',
      size: size,
      resolve: {

         workspace: function () {
          return workspace;
        }

      }
    });

    modalInstance.result.then(function (selectedItem) {
       var index=$scope.workspaces.indexOf(selectedItem)
      $scope.workspaces.splice(index,1);     
    }, function () {
      $log.info('Modal dismissed at: ' + new Date());
    });
  };



    var setAllInactive = function() {
         //angular.forEach($scope.workspaces, function(workspace) {
           // workspace.active = false;
   // });
    };
    var addNewWorkspace = function() {

        var id = $scope.workspaces.length+1 ;

        $scope.workspaces.push({
            id: id,

            name: "Workspace " + id,

        });
        $scope.active=$scope.workspaces.length -1;


    };

    $scope.workspaces =
    [

    ];

    $scope.addWorkspace = function () {
        setAllInactive();
        addNewWorkspace();

    };    


     $scope.remove=function(item){ 
      var index=$scope.workspaces.indexOf(item)
      $scope.workspaces.splice(index,1);     
    }

});

angular.module('plunker').controller('ModalInstanceCtrl', function ($scope, $uibModalInstance, workspace) {

  $scope.selectedworkspace = workspace;

  $scope.ok = function () {
    $uibModalInstance.close( $scope.selectedworkspace );
  };

  $scope.cancel = function () {
    $uibModalInstance.dismiss('cancel');
  };
});




app.controller ("TabsChildController", function($scope, $log){

});

Answer №1

To ensure that the newest tab is active, you need to adjust the code as follows:

$scope.active = $scope.workspaces.length;

However, there is a potential issue with this approach. After pushing a new workspace, it takes time for the directive to update the DOM and prepare all the scope variables. Therefore, trying to set the newest tab as active immediately after push may lead to an error.

As a quick (though not necessarily the best) solution, consider adding a slight delay before setting the active tab. Here's an example of how you can modify your code by injecting $timeout as a dependency:

app.controller("TabsParentController", 
    function ($scope,$uibModal, $timeout) {

        ....
        ....

        $scope.workspaces.push({
            id: id,
            name: "Workspace " + id,
        });

        //introduce a 50 ms delay before setting the active tab
        $timeout(function(){
           $scope.active = $scope.workspaces.length;
        }, 50);

        ....
        ....

    }
);

Experience it on Plunker

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

Can I find a better approach to optimize this code?

How can I refactor this code to move the entire DB query logic into a separate file and only call the function in this current file? passport.use( new GoogleStrategy({ clientID: googleId, clientSecret: clientSecret, callbackURL: ...

What is the best method for directing to various pages on a GitHub Pages website?

My GitHub Pages site is live at this link. While the splash page loads perfectly, clicking on the circle to transition to the next page, 'landing.html', leads to a 404 error. I have exhausted all possible solutions to address this issue, includin ...

I successfully managed to ensure that the splash screen is only displayed upon the initial page load. However, I am now encountering an issue where it fails to load again after I close the page. Is there any possible solution

After successfully implementing a splash screen that only plays once on page load, I encountered an issue. When I close the tab and revisit the page, the splash screen no longer plays. Is there a way to fix this problem? Perhaps by setting a time limit for ...

What is the best way to perform calculations within a PHP loop for <input> elements and then display the results using a JavaScript loop?

Hello everyone, I'm currently struggling with displaying the calculations from a loop of input tags. What I'm trying to achieve is having 5 rows with input fields. At the end of each row, there should be a span area that displays the calculation ...

Exploring deeply nested objects within Express by iterating through them

I am trying to figure out how to iterate through objects in Express.js. I can retrieve information from the JSON file, but when I attempt to loop through it, I keep getting an error saying that it's not defined. What could I be missing here? My goal ...

How can a JavaScript map be created with string keys and values consisting of arrays containing pairs of longs?

Struggling with JavaScript data structures, I am trying to create a map in which the key is a string and the value is an array of two longs. For instance: var y = myMap["AnotherString"]; var firstNum = y[0][0]; var secondNum = y[0][1]; // perform opera ...

The outcome of a function within the $.ajax method is transformed into a string

Trying to pass an array of IDs using the $.ajax data variable is proving to be a challenge. The array is generated by a function, and I've noticed that if I define this function outside of the $.ajax call, it works fine. However, when I place the same ...

In Node.js, JavaScript, when using SQLite, the variables are inserted as Null

I have spent a lot of time searching and trying various methods, but I am still unable to solve this issue. My goal is to insert 8 variables received from an API call into an SQLite table. Although the execution seems correct, when I query the table, all v ...

Manipulating toggle buttons using CSS and jQuery

Check out this jsfiddle to see my attempt at creating a toggle switch in the form of a mute button. The toggle button shows the current setting: mute or unmute When hovered over, it displays the alternative setting However, I am encountering an issue wh ...

Stop Jade from collapsing the directory hierarchy

When it comes to implementing a build solution using NPM scripts instead of Gulp or Grunt, I have been facing some challenges in managing multiple Jade files efficiently. I've referred to resources like and for guidance. The Jade CLI allows for com ...

Unexpected token error occurs when using map-spread operator in vue-test-utils combined with jest

I recently set up testing for my Vue project by following the instructions provided in this helpful guide here Upon completion of the guide, I proceeded to create a test for one of my components. However, when I ran jest, I encountered the following error ...

Reveal Visual Content upon Hovering

Is there a way to show an image only when the mouse hovers over it? Additionally, can we underline the adjacent text at the same time? If the mouse moves away from the image, I'd like it to hide again and revert the text back to its original state. T ...

Retrieving a universal variable within AngularJS

Is there a way to initialize an Angular model using a JSON object that is embedded within an HTML page? Take this as an example: <html> <body> <script type="text/javascript" charset="utf-8"> var tags = [{&q ...

The AngularJS ngModel directive encounters issues when used within a ui-bootstrap tabset

Check out the code snippet below to see the issue at hand: <!DOCTYPE html> <html ng-app="plunker"> <head> <title>AngularJS Plunker</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/cs ...

What are the steps to retrieve historical stock data for over one year using Yahoo Finance YQL query?

I am currently using a Tableau web connector to retrieve stock price data. Here is the source code: <html> <meta http-equiv="Cache-Control" content="no-store" /> <head> <title>Stock Quote Connector-Tutorial</title> <sc ...

Implementing a rate limit on the login API that is specific to individual IP addresses rather than being

I have successfully implemented the [email protected] module, but I am facing an issue where it is blocking the API globally instead of for a specific API that is receiving hits. This is my current code: const limiter = new RateLimit({ windo ...

Navigating to a precise location on a webpage with React.js

I want to implement a straightforward action where the page automatically scrolls to a specific position upon loading. However, my attempts to execute this action have been unsuccessful so far. Is there an alternative method to achieve this in a React ap ...

What is the best way to display the value of a new object's property in Angular?

I am currently developing a list application that allows users to create new lists by entering a name and clicking a button. Once the list is created, users can add and remove items from the list. However, I have encountered an issue where the name of the ...

Decoding JSON with JavaScript following the response from JsonConvert.SerializeObject(json) in a .NET handler

I am currently working on a web application using the .NET platform. I have written a Handler code that returns a JSON object to JavaScript (after making an AJAX request). Here is the Handler code: var wrapper = new { left = left.ToString(), t ...

Creating a Duplicate of the Higher Lower Challenge Game

To enhance my comprehension of React, I am constructing a replica of the website: Instead of utilizing Google searches, I opted for a dataset containing Premier League stadiums and their capacities. Up to this point, I have crafted the subsequent script: ...