Using AngularJS ng-repeat to create tabbed interfaces

In my current scenario, a dynamic number of tabs can be created. When a user clicks on an entry in a commands menu, a new pill-tab pair is added to the existing ones (Note: Bootstrap is used for styling).

The list of tabs is managed within an array in $rootScope. Whenever a new tab needs to be opened, an entry is simply added to the array using the push method. An ng-repeat directive handles the creation of pill-tab pairs.

Everything works smoothly, with tabs and pills being added successfully. However, I'm facing a challenge in setting the newly added tab as the active one immediately upon creation. This is because the creation (addition to the list) happens within a controller and the element is not yet recognized by the DOM.

I considered using a timer, but found this approach to be quite messy and inefficient.

Answer №1

In Angular, one powerful tool you can utilize is the $timeout service:

Check out the documentation on $timeout here

For instance, if you have specific tasks to be executed after a directive is rendered and a controller is initialized, simply append the following code snippet at the end of the controller:

$timeout(function(){ $scope.perform_tasks(); } );

This will ensure that the tasks are carried out after the component's digest cycle completes.

Moreover, $timeout provides good testing capabilities, allowing for control in unit tests.

One feasible approach could involve:

  • Prior to adding a new tab, establish a promise within a parent scope or service
  • Subsequently, once the child controller is set up, implement a promise resolution using $timeout within that child controller

Answer №2

Avoid using timeouts or similar methods because the loading time is unpredictable. My recommendation is to utilize this directive within your ng-repeat:

.directive('onFinishRender', function ($rootScope) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            if (scope.$last) {
                $rootScope.$broadcast("ngRepeatFinished");
            }
        }
    };
});

HTML:

<ul>
   <li class="pages" data-ng-repeat="page in sidebarPages" on-finish-render></li>
</ul>

This code will detect when the last item is rendered in ng-repeat and then send a $broadcast event to the controller. In your controller, you need to listen for that event like so:

$rootScope.$on('ngRepeatFinished', function(event, args) {

    // execute desired actions
});

You can also explore $viewContentLoaded

$scope.$on('$viewContentLoaded', function(event, args) {

    // execute desired actions
});

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

Adding evaluation value to the argument of an onclick JavaScript function in an ASP datalist (Front-End)

Can anyone help me with adding a JavaScript function to my checkbox within a datalist, where the ID of the control is passed as a parameter? I would like to achieve this on an ASP page without using the OnItemDataBound method. I have tried the following c ...

Transform arrays within arrays to objects

I've been struggling to convert a nested array like the one below: var array = [ [['firstName', 'Henry'], ['codeName', 'Etta'], ['email', '<a href="/cdn-cgi/l/email-protection" class="__cf ...

When communicating with the backend in a React application, the data is not being successfully sent using axios. An error message stating "Unsupported protocol

My current setup involves using Express.js as the backend and setting up a proxy to the backend in the package.json file of my React.js project. Initially, I encountered an error when using the fetch method, so I switched to using Axios to resolve this iss ...

Determine if the same origin policy is in effect

Is there a method to determine if the same origin policy is applicable to a URL before attempting to use ajax methods? Below is an example of what I currently have: function testSameOrigin(url) { var loc = window.location, a = document.create ...

Updating the value of a localStorage key after each successful AJAX call in JavaScript

I'm currently facing a challenge with my local storage key value. The issue is that it doesn't update the value when the AJAX call successfully returns data. It only retains the old stored data, requiring me to manually refresh the page by pressi ...

Retrieve the id within the parentheses for each checkbox that is checked and re-check each time a checkbox is selected using Kendo UI

Working with the tricky kendo-ui has made adding selectors quite challenging; however, my current task involves simply obtaining the inner contents of the id selector upon clicking an input checkbox element. Specifically, I need to extract the text between ...

The updating of input and output does not happen instantly; there is a delay before changes

Having an issue with updating input values in React. When using the setState method, the console log does not show the updated input value immediately. For instance, typing "a n" into the input only logs "a" after the second keystroke... Although I under ...

The issue arises when AngularJS binding to a JSON object results in the value being

I am encountering a complex problem with nested bindings in custom directives. The JSON structure I am working with resembles the following; { survey: questions:[ { text:'Question 1', answers:[ { ...

Unlocking the Potential of External Values in Angular Beyond http.then

Here is an example of my controller code: var app = angular.module('myApp'); app.controller('myCtrl', function() { $scope.year = "1350"; $scope.ord1 = ""; $scope.s1t1 = function() { $http({ url: 's1 ...

Solving the Issue of Assigning a Random Background Color to a Dynamically Created Button from a Selection of Colors

Trying to create my own personal website through Kirby CMS has been both challenging and rewarding. One of the features I'm working on is a navigation menu that dynamically adds buttons for new pages added to the site. What I really want is for each b ...

What steps do I need to take in order to make this array equation function properly?

I've developed a Javascript code that calculates the total linear footage based on values entered by the user. Below is the snippet of the JavaScript code... var totalLinealFootage = 0; for (var i = 0; i <= 24; ++i) { ...

Exploring innerHTML in JavaScript for event listening

Two code snippets were tested, one worked as expected while the other didn't produce the desired result. The goal was to display a different text every time a user clicked on a button. However, the unsuccessful code always displayed err, with no chang ...

Resolving the issue of data transmission within Yii2's framework: Page-to-page data

I'm currently using Yii2-advanced-app and I have encountered an issue. I want to pass the selected value from a dropdown menu to a PHP code that displays a list with checkboxes on the same page. Here is an image for reference on what I am trying to ac ...

Listcell XUL with button options

How can I make buttons inside a listcell function in XUL? I am having trouble getting it to work. Here is the XUL code: <listitem id = "1"> <listcell label = "OK Computer"/> <listcell label = "Radiohead"/> <listcell label ...

How can I utilize target.event to close the dropdown in Vuejs when clicked outside of it?

const app = new Vue({ el: "#app", name: 'aselect', data: { value: 'Select a Fruit', list: ["Orange", "Apple", "Kiwi", "Lemon", "Pineapple"], visible: false }, methods: { toggle() { this.visible = !this.vi ...

Streamlined method for creating forms and charts within SharePoint

When it comes to creating charts and forms on SharePoint, what is the best approach for maximizing efficiency? Using AngularJS web parts with CRUD operations. Modifying standard forms and integrating charts using JavaScript libraries and CSS. Are there ...

How to dynamically generate data with exceljs

Currently, I am attempting to download JSON data into an Excel spreadsheet. One of my requirements is to insert an image in cell a1 and then bold the headers. The code snippet below was sourced from Google; however, I need to populate the data dynamically ...

Select2 is not displaying correctly as expected

I followed the instructions on to set up a Select2 select. However, I noticed that my Select2 select doesn't look great. Here is how it currently appears: https://i.sstatic.net/SIv7L.png When I don't transform it with jQuery $('#users&apos ...

Stop the closure of confirmation box by disabling the space key

I've been working on a website that features a table for users to interact with. Within one column of the table, there are input boxes where users can write notes. Below each input box, there is a save button to store the entered notes in a database. ...

Latest Version of Joomla includes Jquery 3.4.3 Files

In my Joomla 3.4.3 setup, while debugging in Firefox using Inspect Element, I noticed a message in the console pointing to http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1.8.21/jquery-ui.min.js. Next to this item, it displays: [HTTP/1.1 404 Not Found ...