Wondering how to execute logic before generating a template in a custom directive?

I am interested in creating a unique custom directive that can take an array of strings and display it as a table. Here is an example of how I envision it:

'string1'  | 'string2'  | 'string3'  | 'string4'
'string5'  | 'string6'  | 'string7'  | 'string8'
'string9'  | 'string10' | 'string11' | 'string12'

To use this custom directive, it should be called like this:

<div class="my-directive" values="values" rowsize="4"></div>

My plan to achieve this is to first divide the values array into smaller arrays based on the given rowsize, and then utilize nested ng-repeat to render the table. The resulting HTML structure within the directive will resemble this:

<table>
    <tr ng-repeat="part in parts">
        <td ng-repeat="value in part">
            {{value}}
        </td>
    </tr>
</table>

In order to accomplish this, I need to perform some initial logic inside the directive (usually handled in the link function) before generating the template (typically defined in the template attribute).

Although this directive could be created using manual DOM manipulation, I prefer following Angular practices for a more streamlined approach.

So, my question remains: How can I implement a custom directive where I can execute initial logic before generating a template?

Answer №1

Here is a solution that should work for you: http://plnkr.co/edit/UYMQtMuZeJRcSQynHUGW?p=info

The main idea is to dynamically generate row objects containing arrays of items. These items are added to the array only if the maximum number of columns allowed has not been reached, as defined by the directive's maxColumns attribute:

In the provided code, you can adjust the value of max-columns in the HTML, and the directive will display the table accordingly:

app.controller('MainCtrl', function($scope) {
  $scope.values = [
    'string1','string2','string3','string4','string5','string6',
    'string7','string8','string9','string10','string11','string12'
  ];
});

app.directive('myTable', function() {

  var templateHtml = 
      '<table border="1">' +
          '<tr ng-repeat="row in rows">' + 
              '<td ng-repeat="item in row.items">{{item}}</td>' +
          '</tr>' + 
      '</table>';

  return {
    restrict: 'E',
    template: templateHtml,
    scope: {
      values: '=',
      maxColumns: '@'
    },
    link: function(scope, element, attrs) {

        scope.rows = [];
        scope.rows.push(_getNewRow())

        function _getNewRow() {
          return { items: [] };
        }

        _.each(scope.values, function(value) {
            currentRow = _.last(scope.rows);
            if (currentRow.items.length < scope.maxColumns) {
               currentRow.items.push(value);
            } else {
               currentRow = _getNewRow();
               currentRow.items.push(value);
               scope.rows.push(currentRow);
            }
        });

    }
  }
});

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

Javascript has ceased functioning on the current server, however it is operational on a different

Need a hand with this tricky issue. The company I'm with has its own website. I've been updating pages on the site for the past few days. After finishing my updates and trying to upload the site, all of a sudden, the JavaScript stopped working. ...

The Mongoose model is having issues being imported into a different Component

Attempting to utilize my model for displaying and locating users in MongoDB has hit a snag. Upon importing it into profile.js and launching my app, an error is thrown: Cannot read properties of undefined (reading 'Users') https://i.stack.imgur.c ...

Disabling eslint does not prevent errors from occurring for the unicorn/filename-case rule

I have a file called payment-shipping.tsx and eslint is throwing an error Filename is not in camel case. Rename it to 'paymentShipping.tsx' unicorn/filename-case However, the file needs to be in kebab case since it's a next.js page that s ...

The directive for accepting only numbers is not functioning in versions of Chrome 49.xx.xx and earlier

I have implemented a directive in Angular 6 to allow only numbers as input for certain fields. The directive code is shown below: import { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: '[NumbersOnly]& ...

Prevent the page from automatically scrolling back to the top when a user clicks on a "read more"

When implementing the function below on an HTML page to show/hide more details about a comment, there is an issue where the page scrolls up to the top whenever the "read more" link is clicked. This can be frustrating as it takes the user away from the comm ...

When working with React, encountering a "TypeError: is not a function" message from a function prop can

I am a beginner with React and I'm attempting to pass a function as a prop to a child component. In this scenario, the parent component looks like this: const [gameStarted, setGameStarted] = useState(false); const [gameSettings, setGameSettings] = use ...

Creating a custom route that is specific to a single ejs file

I'm trying to set up a URL like localhost:3000/hh234due with a unique ID that routes to a specific page. However, my current implementation is conflicting with other routes. How can I make the /:id route unique to one view? module.exports = fun ...

Incorporating essential navigation elements into the interface

I'm working on an AngularJS project where I need to create a view that displays various images within div elements. I want to implement keyboard navigation to allow users to scroll through these images using their arrow keys. Can someone provide guida ...

Error encountered while establishing connection with MongoClient

My server is returning the following error message: MongoClient.connect('mongodb://<'yoda'>:<'yoda69'>@ds235778.mlab.com:35778/satr-wars-quotes', (err, client) => { ^^^^^^^^^^^^^ SyntaxError ...

Dynamically Remove One Form from a Django Formset

I have been using the following code to dynamically add a form to my formset: .html {{ form2.management_form }} <div id="form_set"> {% for form2 in form2.forms %} <table class="table table2" width=100%> ...

Enhance the flight experience of a helicopter with jQuery game by adding smoother controls

I'm currently experimenting with creating a basic game. In this game, the user controls a helicopter and can fly it up and down. Although I have successfully implemented the basic functionality where holding the screen makes the helicopter ascend an ...

How to dynamically add HTML content to a JSON string with the help of Javascript

I am working with a JSON object that includes various messages to be displayed on a webpage using Javascript. This JSON file is located in a separate directory and I have full control over it, being loaded asynchronously. There are specific cases where di ...

Using Dynamic Jinja HTML to Select Elements Dynamically

I have a unique system where forms are dynamically created based on values from a dictionary. Each form is assigned an ID corresponding to the key value and initially hidden. <div id="subforms" style="display: none" > {%for k, v in options.items() ...

I would like to have text show up instead of an alert when validation is triggered

Hey there, I need some help with JavaScript as I'm just getting started. Basically, I want to display the text "please fill in" next to a textbox if the user hasn't entered any information. <!DOCTYPE html> <head> <title>Easy ...

Failed jQuery AJAX request to database with no returned information

I'm really confused about where the issue lies :S The button triggers a function that passes the parameter "sex" and initiates an ajax call to ajax.php, where I execute a MySQL query to retrieve the results and populate different input boxes. When I ...

Analyzing JSON data and creating a tailor-made array

My Dilemma { "rowId": "1", "product_name": [ "Item A", "Item B", "Item C", "Item D", "Item E" ], "product_tag": [ "123456", "234567", "345678", "456789", "5678 ...

What are the benefits of removing event listeners in Reactjs?

In my opinion, the event listeners need to be reliable and consistent. React.useEffect(() => { const height = window.addEventListener("resize", () => { setWindowSize(window.innerHeight); }); return () => window.remov ...

Frontend Navigation with Role-Based Display

I am currently working on a project with a REST API served by Spring Boot, using JWT tokens generated on the backend server. These tokens are then passed to the frontend application built with AngularJS and HTML5. My goal now is to customize the navigation ...

Getting JSON with duplicate keys in JavaScript can be achieved by parsing the data using a custom function

I am attempting to retrieve JSON from a URL, but I have encountered an issue where the response object is removing duplicate keys. Is there a way to fetch the JSON without eliminating these duplicates? Below is my JavaScript code: $('document'). ...

Sending an incorrect value to the data variable

Apologies for my limited proficiency in English, Hello, I am new to Vue and struggling with an issue that I can't seem to resolve. I am fetching art data from an API (a simple list of dictionaries), and then creating a multi-array structure (list of l ...