Building and Choosing Angular Material Tabs

Currently, I am utilizing the md-selected property within the md-tabs directive to manage and select tabs. Whenever a new tab is created, my goal is to automatically have it selected. Although this functionality appears to be working in the provided demo, it is accompanied by errors. Are there alternative methods that could be more effective?

JavaScript:

$scope.addTab = function (title, view) {
  view = view || title + " Content View";
  var newIndex = tabs.push({ title: title, content: view, disabled: false});
  $scope.selectedIndex = newIndex;
};

HTML:

<md-tabs md-selected="selectedIndex" md-border-bottom="">
  <md-tab ng-repeat="tab in tabs" ng-disabled="tab.disabled" label="{{tab.title}}">

Error Message:

TypeError: Cannot read property 'offsetLeft' of undefined
at updateInkBarStyles (angular-material.js:12808)
at Object.handleSelectedIndexChange [as fn] (angular-material.js:12750)
at Scope.$get.Scope.$digest (angular.js:14308)
at Scope.$get.Scope.$apply (angular.js:14571)
at HTMLFormElement.<anonymous> (angular.js:21571)
at HTMLFormElement.eventHandler (angular.js:3032)

http://codepen.io/anon/pen/JdbLda

Answer №1

After some investigation, I found a significant issue with the implementation of your `newIndex` in the add function. It was not properly 0-based, which is crucial as push returns the new length:

The code snippet: 
var newIndex = tabs.push({ title: title, content: view, disabled: false});
$timeout(function() {
  $scope.selectedIndex = newIndex - 1;
});

To resolve this issue, I wrapped the necessary change in a `$timeout` to ensure that `tabs` gets updated before accessing its length.

In addition, I made adjustments to the way `previous` and `selected` are handled by simplifying them to their indices rather than full tab objects (although either approach can be used, just be mindful of comparisons between an `int` and a `tab`). Also, it's important to note that on the initial pass, `selected` is `null`:

The modified line of code:
previous = selected || old;

If you'd like to view the complete solution, feel free to check out the demonstration on this codepen link!

Answer №2

Ever since this query was raised, an additional feature called the md-autoselect flag has been introduced:

md-autoselect boolean
This enables automatic selection of any tabs that are added post initial loading

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

I am experiencing issues with displaying the submenu using CSS and jQuery

I'm experiencing an issue with some code and I seem to be stuck. Could really use some assistance. The submenu is not functioning as expected - when I click the toggle button, the main menu appears but the submenu does not work. I've tried variou ...

How can I trigger a method after the user has finished selecting items in a v-autocomplete with multiple selection using Vuetify?

After multiple selections are made in a v-autocomplete, I need to trigger a method. However, the @input and @change events fire after each selection, not after the full batch of selections. Is there an event that triggers when the dropdown menu closes? Al ...

React - issue with displaying text in list elements

Currently working on a straightforward task list application with React. Within my three components, the one responsible for showing the items ('Item' component) is able to display the bullets but not the actual text. Take a look at my code snipp ...

"Discovering the method to showcase content based on page number or when the 'previous' or 'next'

Here is how my Vue component looks like: <template> ... <b-col v-for="item in items" v-bind:key="item.id" cols="2"> ... <strong slot="header" class="text-dark" :title ...

I am unable to incorporate added height into the component

In my current project using react.js, material-ui, and sass, I had the task of creating a ChatBit component. After writing it, here is the code: customComponent.js file. // @flow import * as React from 'react'; import { useState } f ...

I cannot seem to locate the module npm file

Currently, I am in the process of following a Pluralsight tutorial. The instructor instructed to type 'npm install' on the terminal which resulted in the installation of a file named npm module in the specified folder. However, when I attempted t ...

Generate a dynamic grid layout with cards of varying heights using Material-UI in a React application

I'm attempting to replicate a grid layout similar to this website using Material-UI. However, I'm encountering an issue where the height of one card affects the height of all the other cards in the grid. I've tried using both `direction="row ...

The drop-down menu fails to appear when I move my cursor over it

#menu { overflow: hidden; background: #202020; } #menu ul { margin: 0px 0px 0px 0px; padding: 0px 0px; list-style: none; line-height: normal; text-align: center; } #menu li { display: inline-block; } #menu a { display: block; position: relative; padding ...

Exploring the power of QueryTask in ArcGIS JS API 3 for running multiple queries

When using QueryTask in ArcGIS JS Api 3, I encountered a challenge where I needed to execute multiple queries in one call. After referencing the documentation, I realized that this functionality was not directly supported. This is my current implementatio ...

Tips for utilizing ng-model in an Angular application

<input type="search" placeholder="{{'COMPONENT_PROPERTIES.SEARCH_ICON' | translate}}" ng-model="icon.name" list="classIcon" ng-change="changeFn(icon.name)"> <i class="{{$select.selected}}"></i> &nbsp;&nbsp; {{$s ...

Simple method for extracting data from JSON and saving it into an array with jQuery

I have a JSON file containing the resource "A" and literals "B", "C", and "D". My goal is to extract only the items B, C, and D, convert them into strings, and store them in an array. Below is the script I have written for this purpose: <script> // ...

The JSON field is missing from the GET response in mongoose

I am dealing with a JSON document (found in mongolab): { "_id": { "$oid": "566e8673eb862d165fef7171" }, "street": "Dizingof", "buildingNumber": 33, "apartmentNumber": 63, "beds": 3, "owner": { "_id": { ...

Ways to showcase angular scope data within a placeholder while avoiding the use of angular expressions

Initially, I utilized angular expressions {{value}} to present values within elements. However, upon noticing that unrevealed expressions continue to display on the front end during loading delays, I switched to using ng-bind. <div> <h1>Hell ...

Encountering issues with scope: Unable to retrieve value and receiving an error message stating 'Cannot assign value to undefined property'

var mainApp = angular.module("Main", []); mainApp.controller("CtrlMain", [ function ($scope) { $scope.amount = 545 }]);` var app = angular.module("Main", []); app.controller("MainCtrl", [ function ($scope) { $scope.value = 545 ...

Angular controller handling a resolve operation

I have a scenario where I need to load ngResources in my global/main controller and pause the execution of anything else until they are loaded, similar to how the resolve property works for routes. How can I achieve this? // Implementing one-time action ...

Obtain the existing text from the <select runat="server"> element

Similar Question: Retrieve Text Selection with Runat=“Server” 1: HTML <div id="dialog"> <select id="Select1"> <option>1</option> <option>2</option> <option>3 ...

Effective ways to check for the time discrepancy between dates in moment.js

My server is set to use UTC date format and I am running my node server in UTC as well. I am looking to determine if the current time in Indian timezone (which is +5.30) is greater than 8AM, and if so, send an email notification. How can I achieve this u ...

When using the `console.log()` function in JavaScript, the table formatting may

I'm attempting to generate a table using JavaScript Here's the HTML for the table: <table id="rounded" runat=server summary="2007 Major IT Companies' Profit" style="position:relative;left:-45px;" > <tr> <th sc ...

Discover how to measure the distance between two clickable points using OpenLayers 6 API

In my api.py file, I have defined some points like this: (...) @app.route('/api/pontos/', methods=['GET']) def get_pontos(): return jsonify({ 'pontos': [ [-44.3001,-2.52001, 3, "name1"], [- ...

Error: An unexpected symbol '||=' was found

I'm facing an issue while trying to create a nextjs project with PDFViewer using @react-pdf-viewer. The error I encountered is "SyntaxError: Unexpected token '||=' when collecting pages. This problem seems to be originating from pdf.js in t ...