Get rid of the tr element if it does not contain any child elements when using ng-repeat in

When using ng-repeat to build a table row inside a table based on specific logic using the "row" value, empty tr elements are being generated. How can these be removed?

This code is resulting in 2 empty tr elements at the end of the tbody.

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

app.controller('MainCtrl', function($scope) {

$scope.data = [
{
    "name" : "John",
    "row" : 1
},
 {
    "name" : "Mike",
    "row" : 2
},
 {
    "name" : "Bill",
    "row" : 1
},
{
    "name" : "Alice",
    "row" : 3
},
{
    "name" : "David",
    "row" : 2
}
 ]
 });



app.directive('specrow', ['$compile', function($compile) {
return {
  restrict: 'A',
    scope : {
      'specobj' : '=',
      'specitemindex' : '='
    },
    link: function (scope, elem, attrs){
      var template = "<td><span>{{specobj.name}}</span></td>";
        var linkFn = $compile(template);
        var content = linkFn(scope);
        var trEl = angular.element(elem[0].parentElement.children).eq(scope.specobj.row-1);
        if(trEl.length === 0) {
          elem.append(content);
        }else{
          angular.element(elem[0].parentElement.children).eq(scope.specobj.row-1).append(content);
        }  
    }
  }
}]);

Plnkr : http://plnkr.co/edit/I3kl9U41n3VzQvqFfG4G?p=preview

Answer №1

Finally, the solution is here!

const app = angular.module('app', ['angular.filter']);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.data = [
    {
        "name" : "John",
        "row" : 1
    },
     {
        "name" : "Mike",
        "row" : 2
    },
     {
        "name" : "Bill",
        "row" : 1
    },
    {
        "name" : "Alice",
        "row" : 3
    },
    {
        "name" : "David",
        "row" : 2
    }
  ]
});
table, th, td {
   border: 1px solid black;
} 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.1.1/angular-filter.min.js"></script>

<body ng-app="app">
    <table ng-controller="MainCtrl">
      <tbody>
          <tr ng-repeat="row in data |groupBy: 'row' | orderBy : 'row'">
          <td ng-repeat="person in row">{{person.row}}.{{person.name}}</td>
              
          </tr>
      </tbody>
    </table>
  </body>

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

Stop the link height from changing when hovered over

Incorporating Angular, Angular Material, and Angular Flex-Layout, I have designed a collection of links that resemble cards or tiles. The links initially display an icon and title but transition to show informational text upon hovering. However, for links ...

Generate an image on Canvas using a URL link

I have a unique URL that generates canvas images with specific parameters. It functions properly when loaded in a browser. The final line of code is: window.location = canvas.toDataURL("image/png"); However, when attempting to use this URL from another ...

Access your Vue.js application using Google Sign-In (GIS)

Having trouble with the discontinuation of gapi.oauth2 by Google and finding the new Sign in With Google tools confusing. Project Structure Looking to implement user sign-in with Google on my Vue frontend and authenticate them using OIDC server flow on ...

Perform operations such as addition, subtraction, and comparison of date and time in Meteor Mongo

Currently, I am working with a collection on Meteor Mongo that includes two important fields: last_activity and expire_date. One scenario involves retrieving items from this collection based on their last_activity being N hours in the past. In another si ...

If statement utilized for conditional looping

As I dive into the world of basic JavaScript, I'm eager to understand how to loop back to the beginning of a method under specific conditions. Consider this scenario: in order for the program to progress to the statement "The character you typed was, ...

Establish a many-to-many relationship in Prisma where one of the fields is sourced from a separate table

I'm currently working with a Prisma schema that includes products, orders, and a many-to-many relationship between them. My goal is to store the product price in the relation table so that I can capture the price of the product at the time of sale, re ...

There was an unexpected error in angular.js while trying to work on a calendar widget based on angular-ui-calendar. The error message indicated that the argument 'fn' was expected to be a function but instead received Moment

I came across a similar topic earlier on Stack Overflow, but unfortunately, the issue wasn't resolved. So, I've decided to revisit this question and address it myself this time. In my app.js file, which is where my main module for the app is ini ...

What is the best way to save multiple instances of a JavaScript function with varying parameters in an array and execute them

I'm looking for a way to efficiently reuse a function multiple times with different ids depending on various conditions, such as select values. Instead of creating a new function for each id, I want a more dynamic approach to handle the potential mult ...

Determine the latitude and longitude coordinates of the edges of the ground overlay based on the data in the

I am trying to determine the corner coordinates in latitude and longitude of a ground overlay provided in a kml-file using either php or javascript. For example, I need to convert from: <LatLonBox> <north>60.406505416667</north> ...

Determine the identifier of the subsequent element located within the adjacent <div> using jQuery

I have a form with multiple input elements. While looping through some elements, I need to locate the id of the next element in the following div. You can find the complete code on jsfiddle $(":text[name^=sedan]").each(function(i){ var curTxtBox = $(thi ...

Discover how to utilize images encoded in base64 format within webhook embeds on Discord

Can someone help me with inserting an image into a Discord embed using a webhook? I have the image saved as a base64 string obtained from a database. However, my attempts so far have only resulted in an empty embed. https://i.sstatic.net/CVs4j.png const d ...

Issue with the Core php code - In relation to the onclick and onload events

The code below is currently functioning correctly: <a href ="#" onclick="accept ("<?php echo $getservice [$i]['id']; ?>, document.frml)"> Accept </a> In the above code, a Javascript function is being ca ...

Creating a custom Higher Order Component to seamlessly connect react-relay and react-router using TypeScript

Hey there! So, my Frankenstein monster project has decided to go rogue and I'm running out of hair to pull out. Any help would be greatly appreciated. I've been working on setting up a simple app with React, React-Router, React-Relay, and Typesc ...

Error message: "Upon initial loading, Angular and Firebase are unable to map undefined"

After the initial load, it functions properly. However, I am seeking a way to implement a promise to prevent data mapping before it has fully loaded. Upon the first loading of the site, the error below is displayed. This issue may arise from attempting to ...

Is it possible to provide an offset to the raycaster in three.js?

I am currently working on developing a pool game using three.js. As part of the gameplay, I have incorporated a helper ruler that indicates the direction of the hit. This ruler is represented by an ArrowHelper and is positioned at y=0, which aligns with ...

What could be the reason for getElementsByClassName failing to work on dynamic HTML elements?

I'm currently in the process of generating multiple dynamic HTML tables and assigning a class to each one. Here's an example: var x = document.createElement("TABLE"); x.className = "table_pos_parts"; //var row = x.insertRow( ...

JSON Error: Attempting to access the value of a key that is undefined

I've been working with an API and managed to successfully load a JSON array of objects in my browser. Here's a snippet of what it looks like: 0: source: {id: null, name: "Protothema.uk"} author: "james bond" title: " A TITLE" description: "A DES ...

Generate selection choices by looping through a JSON document

I am attempting to develop a search box that will provide autocomplete suggestions based on user input from a key-value pair in a json file. I initially thought using datalist would be the most suitable approach for this task, however, upon running the cod ...

Looking for a script to automate clicking on a specific web element using JavaScript

When working with Selenium, we utilize an action to interact with an element by clicking on it at specific coordinates (X, Y). action.MoveToElement(element, X, Y).Click().Build().Perform() I am looking to achieve the same functionality using Javascript. ...

Add a prefix to a value entered by the user

I need help with adding a prefix to an input field value using Jquery. I want the input field value to be submitted as "Referrer Email: {email address}" where the {email address} part will be dynamic. The snippet below is what I found, but I'm having ...