Dealing with problems in displaying table rows using Angular Directives

As a novice Angular programmer, I am on the cusp of grasping directives.

I decided to create a fiddle here, even though I am unfamiliar with it, and unfortunately, it's not rendering properly...

The tr-row is a directive that aims to loop through the data and generate a row for each record. HTML:

<table ng-controller="fiddleCtrl">
   <thead>
      <th>id</th>
      <th>name</th>
      <th>description</th>
  </thead>
  <tbody>
    <tr><tr-row ng-repeat="d in data" scdata="d"></tr-row></tr>
  </tbody>
</table>

Javascript:

var myapp = angular.module('myApp', [])
.controller('fiddleCtrl', ['$scope', function ($scope) {

$scope.data = [
     { id: 1, name: 'Fred',   description: 'not the best worker' }, 
     { id: 2, name: 'Wilma',  description: 'Freds Wife'}, 
     { id: 3, name: 'Barney', description: 'Freds best friend'}, 
     { id: 4, name: 'Louise', description: 'Never heard of Fred'}, 
     { id: 5, name: 'Tracy',  description: 'Some Chick'}, 
     { id: 6, name: 'Foo',    description: 'Inventer of bar'}
];
}]).directive('trRow', function ($compile) {
return {
    restrict: "E",
    replace: true,
    link: function (scope, element, attrs) {
        scope.id = scope.d.id;
        scope.name = scope.d.name;
        scope.desc = scope.d.description;

        var tmpl = '<tr  ><td>{{id}}</td><td><strong>{{name}}</strong></td><td>{{desc}}</td></tr>';
        element.html(tmpl).show();
        //var e =$compile(tmpl)(scope);
        //element.replaceWith(e);
        var e = $compile(element.contents())(scope);
    },
    scope: {
        d: "="
    }
};
});

This should be straightforward. (sigh)

Any assistance would be greatly appreciated as I am eager to comprehend this.

The issue with my code is that the tr-row directive is replacing the entire table. It generates a list of rows but without a table to contain them. I understand I am on the right track, but I'm running out of ideas to try.

All I need is a basic table with rows.

I apologize if this question has been asked numerous times before, I'm unsure of what keywords to search for. I've attempted various solutions without success.

Answer №1

Firstly, you cannot have a tag name with a dash character. Therefore, using tr-row as a tag name is not allowed, but you can use it as an attribute.

To work around this limitation, you can create a directive like the following:

.directive('trRow', function () {

    return {
        template: '<tr><td ng-bind="row.id"></td><td><strong ng-bind="row.name"></strong></td><td ng-bind="row.description"></td></tr>'
    };
});

Usage of this directive would look like this:

<tbody>
    <tr tr-row ng-repeat="row in data"></tr>
</tbody>

You can see a working example in this fiddle: http://jsfiddle.net/T7k83/86/

Answer №2

This issue is specific to <table> elements.

Browsers parsing engines do not handle invalid tags inside <table> well, causing them to attempt to remove your directive from the table before it can be replaced with valid elements (you can confirm this by inspecting the element). This behavior applies even if your directive does not contain a dash in its name.

To resolve this issue, consider using directive type A instead of type E, as recommended by @MuratCorlu.

For other elements like <div>, you can simply replace them with custom tags that include dashes in their names. For instance, ng-repeat could serve as a tag replacement.

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

Utilizing the this.setState function within a callback

In my current project, I've encountered an issue with setting the state in a Twitter timeline react component. The code snippet causing trouble is as follows: componentWillMount: function() { twitter.get('statuses/user_timeline', ...

exciting, showcasing a dependency map using svg within an html5 environment

I am working on creating a polygon background for my menu, which needs to be responsive in design. Here is an example of what I am trying to achieve: example image. Should I use JavaScript to listen for size changes and adjust the points for the polygon e ...

What reasons underlie the existence of various methods for importing Modules in JavaScript?

I'm confused about the distinctions when it comes to importing a JavaScript module in various ways such as: CommonJS ES5 ES6 NodeJS Typescript What is the reason for having multiple methods of importing JavaScript modules? Is the concept of a "modu ...

If the list item is the first or second child, align the menu to the right

I've been facing some challenges with my mega menu implementation. The dropdown appears either on the left or right side based on calculations of offset.left, but it seems to behave differently across various screen resolutions. As a solution, I&apos ...

Twitter API causing issues with setTimeout function in Node.js

Attempting to read from a file and tweet the contents in 140 character chunks, one after the other has proven to be quite challenging. Despite verifying that other parts of the code are functioning correctly, using a simple for-loop resulted in tweets bein ...

NodeJS Promise fails to execute the third 'then()' method

One of the promises I have made involves logging into a website and gathering information. Here is the code I have written: var Promise = require('promise'); function login(user, pass){ // Code implementation for logging in and gathering in ...

Struggling to manage the flow of my program, constantly switching back and forth between handling AJAX callbacks and rendering PIXI

I'm struggling with optimizing the flow of my JavaScript script. The script is responsible for receiving and sending mouse coordinates to be drawn. Take a look at the code snippet below: //Initializing PIXI var stage = new PIXI.Stage(0x000000); var ...

Identifying an Android device using Javascript or jQuery

Is there a way to identify an Android device for styling a mobile website? I want to add specific CSS styles for users on the Android platform. Appreciate any help! ...

ng-touched remains unchanged after calling .markAsUntouched on a Custom Control

Editing a field in an Angular 2 form with a custom control and resetting it using .markAsUntouched does not remove the ng-touched class. The sample form structure is as follows: <form #editForm="ngForm"> <input [(ngModel)]="title" name="titl ...

Exploring Decimal Bitwise Operations in C# using JavaScript as a reference

Currently in the process of translating a library from JavaScript to C# and encountered the following scenario: // In JavaScript var number = 3144134277.518717 | 0; console.log(number); // -> -1150833019 After researching other posts, it seems that th ...

Ways to retrieve a variable from outside of a function

I am in need of sending the following batch data to the database, but I am facing difficulties in including the course_id along with the batchData. Currently, I am retrieving the course_id from another service that fetches data from a course table. I am ...

Navigating Date Conversion within Component in Angular 2 Application

Searching for a way to update the display of certain dates in my Angular 2 application, I encountered a roadblock. Using the date pipe in conjunction with string interpolation wasn't viable due to the structure of my template code: <input class="a ...

Utilize a PHP-AJAX request to retrieve JSON data and then transfer the data to JGauge.js in order to display the value

scenario where I need to transfer an ajax-called value to another script (specifically a widget script) within the same file, I have managed to successfully execute the ajax call and implement a justgage widget on a single page. While I can effectively dis ...

The outcome of the mongoose .exists function in JavaScript is a boolean value

Currently, I am delving into the world of node.js and mongoDB. For a project I'm working on, I've set up a demonstration login system to practice my skills. In my main API, I have a function that checks whether a refreshToken exists in the mongo ...

Discovering a particular string within a jQuery array object: Tips and tricks

One thing that is confusing me is the jQuery array object. To explain further: I have two arrays, one called brandsLink and the other called floorLink. When a user clicks on a link, I am saving the brand name in a variable called brandName, and then checki ...

Discover an Element within a JSON Array and Append a New Value to it

I've got an array of JSON data structured like this: [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Eve' } ] My goal is to locate an object by its id and append a ...

Using JavaScript to extract information from a dropdown menu

Currently, I am working on a project that involves reading values from a dropdown box on a webpage and alerting the selected value. Below is the code I have written for this task. JavaScript function main(input) { value = getValue(); alert(value) ...

Can you explain the distinction between these two Redux reducer scenarios?

While looking at someone else's code for a reducer, I noticed this snippet: export default function reducer(state, action) { switch(action.type) { case 'ADD_TODO': Object.assign({}, state, { ...

What is preventing me from being able to import a React component from a file?

I've double-checked my code and everything seems correct, but when I view it on the port, only the app.js file is displayed. import React from 'react'; import ImgSlider from './ImgSlider'; import './App.css'; function ...

Ways to store information in variables and use it across different blocks in Cypress

Is it feasible to store data in variables and reuse them in other blocks within Cypress.io? For instance, imagine I have a unique name for a device. I aim to retrieve this information and then verify if the title in a new window includes that particular de ...