Struggling to create a <td> with AngularJS directive

I am currently working on creating a directive for a large set of repeated HTML code that involves using tables and table data cells. Although I have experience creating directives for div elements in the past, this is my first attempt at incorporating them into <table> / <td> elements.

Here is an example of the HTML structure:

<div ng-repeat="entries in Categories">
    <table>
        <tbody>
            <tr ng-repeat="history in entries.InfoEntries">
                <th>
                    {{ history.Name }}
                </th>
                <td ng-repeat="status in history.History.slice(0, 12) track by $index">
                    <span ng-switch="status">
                        <span ng-switch-when="0"></span>
                        <span ng-switch-when="U">U</span>
                        <span ng-switch-when="D">D</span>
                        <span ng-switch-default></span>
                    </span>
                </td>
            </tr>
        </tbody>
    </table>

    <!-- More similar table structures here -->

</div>

The only thing that varies between these tables is the range of values used in the .slice function. To incorporate this variability into my directive, I plan to pass in the start and end ranges as attributes:

<td history-status slice-start='0' slice-end='12'></td>

This is what my directive looks like:

app.directive('historyStatus', function () {
return {
    restrict: 'A',
    replace: false,
    transclude: true,
    template:   '<td ng-repeat="status in history.History.slice(sliceStart, sliceEnd) track by $index">' +
                    '<span ng-switch="status">' +                            
                        '<span ng-switch-when="U">U</span>' +
                        '<span ng-switch-when="D">D</span>' +
                        '<span ng-switch-default></span>' +
                    '</span>' +
                '</td>',
    scope: {
        sliceStart: '=sliceStart',
        sliceEnd: '=sliceEnd'
    }
  };
});

Despite implementing the above directive, I am not seeing any output rendered on the page, and there are no error messages being displayed in the browser console.

Answer №1

Perhaps the issue stems from the fact that you have isolated the directive's scope, requiring you to pass 'history' explicitly:

HTML:

<td history-status history="history" slice-status-history-start-range='0' slice-status-history-end-range='12'></td>

In your directive:

scope: {
        sliceStartRange: '=sliceStatusHistoryStartRange',
        sliceEndRange: '=sliceStatusHistoryEndRange',
        history: '='
    }

Answer №2

Invalid markup will be generated if you insert a 'td' element inside another 'td'.

Ensure that the 'replace' attribute is set to 'true'. Code snippet: http://plnkr.co/edit/hk9GJ7tiL0VANhcSiBax?p=preview

<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.js"></script>
<script>
  angular.module("ng").directive('historyStatus', function () {
    return {
        restrict: 'A',
        replace: true,
        template:   '<td ng-repeat="status in datasrc track by $index">' +
                       '<span ng-switch="status">' +                            
                            '<span ng-switch-when="U">U</span>' +
                            '<span ng-switch-when="D">D</span>' +
                            '<span ng-switch-when="1">1</span>' +
                            '<span ng-switch-when="2">2</span>' +
                            '<span ng-switch-when="3">3</span>' +
                            '<span ng-switch-when="4">4</span>' +
                            '<span ng-switch-when="5">5</span>' +
                            '<span ng-switch-when="6">6</span>' +
                            '<span ng-switch-default></span>' +
                        '</span>' +
                    '</td>',
        scope: {
            sliceStartRange: '=sliceStatusHistoryStartRange',
            sliceEndRange: '=sliceStatusHistoryEndRange',
            datasrc: '=datasrc'
        }
      };
    }).run(function($rootScope){

    });
</script>
</head>

<body ng-app>
  <table ng-init="datasrc=['1','2','3','4','U','A']">
    <tbody>
      <tr>
        <td datasrc="datasrc" history-status slice-status-history-start-range='0' slice-status-history-end-range='12'></td>
      </tr>
    </tbody>
</table>
</body>

Answer №3

Check out the code sample I promised.

If you have any more questions, feel free to ask!

Remember, you can also utilize the hasStatus scope variable in your classes.

   <span> {{ "UD123456".indexOf(status)>-1 ? status : '-' }}</span>

Hope this clarifies things a bit for you!

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

Auto-collapse sidebar upon clicking anywhere on the page

I have a dynamic sidebar that appears when the user clicks on a hamburger button. Here is the layout: $('#nav-toggle').click(function() { if($('#nav-toggle').hasClass('active')){ $('.menu').animate({ r ...

Steps to remove information from a database using PHP, AJAX, and vanilla JavaScript (without jQuery)

I am facing an issue with deleting data from my database. Whenever I click on the delete button, it deletes the first row instead of the intended row. Below is my PHP code: <?php $connect = mysqli_connect("localhost","root","","abu"); if($conne ...

Is it feasible to display a message for a certain duration without using the alert() function upon clicking a button?

I'm working on a NEXT.JS project and I need to display a <p> element under my button for a specific duration before it disappears. I don't want to use the alert() function. Any suggestions on how to achieve this? ...

The UI bootstrap dropdown toggle requires two clicks to reopen after being manually closed

Utilizing the UI Bootstrap drop-down element to display the calendar from angular-bootstrap-datetimepicker upon clicking. Additionally, a $watch has been implemented to close the dropdown once a date is chosen. Access the Plunker here <div uib-dropdow ...

What is the best way to fetch information from an API using Angular5 with Material2 components?

Here are the 'table.component.html' and 'table.component.ts' files where I am pulling data from an API to display in a table. Below is the object received from the API: [ {position: 1, name: 'Hydrogen', weight: 1.0079, sym ...

Tips for invoking or triggering the Ajax change function when there is only a single option available

<select class="custom-select custom-select-sm mb-3" required="true" id="sel_block"> <option value="0">Select Block From Here</option> <?php // Fetch Blocks $sql_block = "SELECT * FROM blocks WHER ...

When using Node.js with Mongoose, you will receive a single object value instead of multiple values in an array

data=[{ locId: '332wn', locadetails: [ { loc: 'ny', status: true }, { loc: 'ca', status: null ...

The JSON object is coming back as null

I need some clarification on why I am getting an "undefined" alert. Any assistance you can offer would be greatly appreciated as this problem is holding up progress on a crucial project. JavaScript $.getJSON("item-data.json", function(results) { ...

Verification upon button press for a form

Currently, I have a form with multiple textboxes that are being validated using the Required Field Validator. However, there is also a captcha control that is not getting validated. I can validate it using JavaScript though. At the moment, an alert pops u ...

What causes the variance in the node_modules directory between a project being installed locally versus globally?

Imagine I have a project called X, which depends on another package, Y. Y in turn has its own dependency on Z. When I run npm install Y in my project, the structure of my node_modules folder is as follows. Take note that Z is installed as a direct depend ...

Having difficulty accessing information from JSON files with Angular JS

There appears to be empty data being added to the table. https://i.sstatic.net/cimze.jpg I'm encountering difficulty retrieving data from a Json file using Angular Js. I've been attempting to fetch the Json data from a URL by clicking a functio ...

Adding a unique value to an array using JQuery when it does not already exist

In need of assistance with a function that is supposed to add values to an array if they do not already exist. var category_json = new Array(); $.ajax({ type: 'POST', url: "<?php ech ...

Saving the Structure of an XML Document Using JQuery

Xml: <Data> <Cat> <Name>Fluffy</Name> </Cat> <Cat> <Name>Willy</Name> </Cat> </Data> JQuery: // ...Executing ajax requests... $(xml).find('Cat').each(function ...

AWS Cognito - ECS Task Fails to Start

I'm facing an issue with using JavaScript to execute a task in ECS Fargate. AWS suggested utilizing Cognito Identity Credentials for this task. However, when I provide the IdentityPoolId as shown below: const aws = require("aws-sdk"); aws.co ...

Tips for resolving an issue with an overflowing Uber React-Vis multicolor bar chart

I am trying to create a multi-colored bar chart using Uber's react-vis library. However, I am encountering an issue where the leftmost bar of the chart is overflowing below the YAxis instead of remaining contained to the right of it. You can view the ...

Execute two tasks simultaneously in two separate workers utilizing the cluster module in node.js

I'm currently diving into clustering with NodeJS. My goal is to have two separate tasks - one handling node-sass and the other managing uglifyjs - each running on a distinct worker using cluster in NodeJS. The code I've implemented seems to be fu ...

Utilizing jQuery to establish various AJAX requests through functions on page load and button click

Utilizing a basic ajax call both on page load and click events, where I have defined separate functions for each. Despite using different URLs and parameters in the function, the JSON data from the previous call is still being displayed when clicked. Bel ...

JavaScript HTML content manipulation

Why doesn't this code work? innerHTML cannot handle something so complex? <html> <head> <script type="text/javascript"> function addTable() { var html = "<table><tr><td><label for="na ...

Can you provide a guide on how to retrieve an HTML file using JSON?

There is a problem with fetching files in different formats. Specifically, I want to retrieve an HTML file that needs to be embedded in an iFrame. Currently, my AJAX request only retrieves SWF files. Is there a way to call and fetch the HTML file instead ...

Exploring Substrings in jQuery/JavaScript

Issue Can anyone help me with locating a specific set of words within a string (gval in this scenario) that defines the specific wordset? if (gval.indexOf("define") > -1){ console.log("Hey! gval has Define"); } var gval = input.val().trim().toLowe ...