Displaying two distinct tables utilizing ng-repeat by employing customized directives

I'm facing an issue with a custom directive that generates tables and is appearing twice on my index page. The data for these tables comes from the $scope.globalrows variable. Even though globalrows contains 2 arrays, it always displays the second array's values. I need to find a way to modify either my template or directives so that each table shows unique values without overwriting each other's contents.

Problem: Both tables are showing up but with the same content from the second table, leading to an overwrite of the first table.

index.html

<grid-print section="1"></grid-print>
<grid-print section="2"></grid-print>

template : print.dir.html

<form class="form-horizontal clearfix">
    <table class="grid table table-bordered">
      <thead>
        <tr>
          <th ng-repeat="col in cols">{{col.title}}</th>
        </tr>
      </thead>
      <tbody>
          <tr ng-repeat="row in globalrows track by $index" index={{index}}>
            <td ng-repeat="col in cols">          
              <span>{{ row[col.field] }}</span>
            </td>  
          </tr>
      </tbody>
    </table>
    </form>

directive:

.directive("gridPrint", function($sessionStorage, dataservice) {
    return {
        restrict: 'E',
        templateUrl: "components/print/templates/print.dir.html",
        replace: true,
        controller: function($scope, $state, $attrs) {
            //array of the items that are to be displayed on the 2 tables  
            $scope.globalrows = dataservice.getCollectionData();          

        },
        link: function(scope, element, attributes){
           // console.log("in grid print"+attributes['section']);            
        }
    };
})

Another directive that generates rows, cols:

.directive("grid", function() {
    return {
        restrict: 'E',
        templateUrl: "components/section/directives/section.shared.dir.html",
        replace: true,
        controller: function($scope) {
            $scope.$on('ready-to-render', function(e, rows, cols) {
               // console.log(rows, cols);
                $scope.globalrows.rows = rows;
                $scope.cols = cols;
            });
        }
    };
})

globalrows array

https://i.sstatic.net/ohlPw.png

Answer №1

Your current directive is not creating any child scope, which means it is sharing the same scope throughout the page. This results in both tables getting updated when data is changed in either of them.

To fix this issue, create a new directive with an isolated scope like scope: { ... }. This way, each directive will function as an individual component and data can be passed to the directive from isolated scope properties. In this case, data1 and data2 are dynamic table data values that need to be supplied by the consumer of the directive. To improve your directive, consider moving the service call out of the directive controller and into a parent controller where the directive elements reside.

Example Markup:

<grid-print section="1" columns="cols" table-data="data1"></grid-print>
<grid-print section="2" columns="cols" table-data="data2"></grid-print>

Example Controller:

// If data is arriving from a method
 dataservice.getCollectionData().then(function(data){
       $scope.globalrows = data;
       $scope.data1 = $scope.globalrows[0];
       $scope.data2 = $scope.globalrows[1];
});

$scope.cols = $scope.columns; //array of columns

Directive Implementation:

.directive("gridPrint", function($sessionStorage, dataservice) {
    return {
        restrict: 'E',
        templateUrl: "components/print/templates/print.dir.html",
        replace: true,
        scope: {
           tableData: '=', 
           columns: '=' 
        },
        link: function(scope, element, attributes){
            // DOM manipulation goes here if required           
        }
        controller: function($scope) {
            // Initialize data arrays if they are undefined
            if(angular.isUndefined($scope.tableData)){
              $scope.tableData = [];
            }
            if(angular.isUndefined($scope.columns)){
              $scope.columns = [];
            }
        }
    };
})

Template (print.dir.html):

<form class="form-horizontal clearfix">
<table class="grid table table-bordered">
  <thead>
    <tr>
      <th ng-repeat="col in columns">{{col.title}}</th>
    </tr>
  </thead>
  <tbody>
      <tr ng-repeat="row in tableData track by $index" index={{index}}>
        <td ng-repeat="col in columns">          
          <span>{{ row[col.field] }}</span>
        </td>  
      </tr>
  </tbody>
</table>
</form>

Plunkr Demo Here

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

Activating a link without clicking will not trigger any javascript functions

I have been attempting to display an image when I hover over a link, but for some reason, the .hover() event is not functioning as expected. Initially, I am just aiming to have an alert pop up. Once I have that working, I can proceed with fading elements i ...

How can I make sure that my function returns a mutated object that is an instance of the same class in

export const FilterUndefined = <T extends object>(obj: T): T => { return Object.entries(obj).reduce((acc, [key, value]) => { return value ? { ...acc, [key]: value } : acc; }, {}) as T; }; During a database migration process, I encounte ...

The difference between importing CSS in JavaScript and importing it directly in CSS lies in the way

Hello there, I am just starting out with web development and learning about Vue.js. In Vue 3, the recommended way to import CSS files from different packages is as follows: Method 1: Import directly in app.js //app.js import '../css/app.css'; i ...

The table will remain empty for eternity as the page is being loaded using ngRoute

Currently, I am utilising Angular routers. app.config(function($routeProvider) { $routeProvider .when('/comment/list', { templateUrl: 'commentList.htm', controller: 'mainController' }) }); ...

Having trouble with Ajax not sending data to PHP in JSON format

After attempting various methods using different ajax techniques, I still cannot get this to work. Being new to ajax and json, I initially thought that the issue might be due to the data not being in a proper form. However, other ajax processes structured ...

Using VBA to Populate Dropdown List on Webpage from an iFrame

I am facing an issue with my code that aims to interact with a webpage by clicking on a link and then modifying dropdown lists within an Iframe. Specifically, I am attempting to populate the Manufr dropdown list based on data from the Year iFrame using VBA ...

Issue: Proper handling of data serialization from getStaticProps in Next.js

I've been working on Next.js and encountered an issue while trying to access data. Error: Error serializing `.profileData` returned from `getStaticProps` in "/profile/[slug]". Reason: `undefined` cannot be serialized as JSON. Please use `nul ...

Having trouble with your Ajax post request?

I am currently working on creating a form that allows users to input information and submit it without the page refreshing. The processing of the form data will occur after the user clicks the submit button. To achieve this, I am utilizing jQuery and Ajax ...

Creating interactive navigation bar effects with scroll and click functionality using jQuery

Is there a way to make the navigation highlight when a user clicks on it and also scrolls to the corresponding section? Currently, I am facing an issue where only the third navigation event highlights, most likely because when navigating to the fourth or f ...

What is the best way to eliminate additional values depending on the one I have chosen?

When utilizing the Vuetify v-autocomplete component with the multiple prop, we are able to select multiple values. How can I deselect other values based on the value I have selected? For instance: If I choose the main value, all others will be deselecte ...

Transforming JSON output into a string without any prior understanding

My AJAX function generates a JSON output which also includes unnecessary XML due to an error in the JSON WebService. To remove this XML, I have utilized JavaScript Regular Expressions. AJAX Function function setJsonSer() { var strWsUrl = 'https: ...

What is the best way to create a jumping animation for an object in Cannon.js and Three.js?

During my quest for a solution, I came across a common practice where users used cannonBody.velocity.y = JUMP_VELOCITY to make an object jump. However, in my scenario, this method only worked while the object was already in motion and not when it was stat ...

In Three.js, FBX bones exhibit smooth rotation, but GLTF bones display strange rotation behavior

Currently, I have successfully implemented a dynamic model that works with an FBX file using the Three.js FBXLoader. However, for convenience sake, I decided to switch to using a GLTF/GLB file as it contains textures within the same file. To achieve this, ...

I am interested in setting up a flickr gallery where clicking on an image will display a pop-up showing the image along with its relevant tags, title, and photo ID

Page´s photo Hello there, I am currently working on creating a Flickr API using JavaScript and HTML. My goal is to search for photos and display them in an HTML page, but I'm struggling with implementing a pop-up feature that includes the photo' ...

Node.js is encountering an error with the post method where req.body is returning an empty

When utilizing cURL or Postman, the operations perform as anticipated curl -d 'username=Johny Sample&title=My First Post&description=We need some assistance cleaning up after the hurricane&postID=Johny Sample_1' http://localhost: ...

I am looking to incorporate a new "ID" column into my mui data grid table in ReactJS that will incrementally count from 0 to the total number of rows

When displaying data from an API in a datagrid table component with multiple columns, it is necessary to include a column for the ID which should have values ranging from 0 to the number of rows. Currently, the Object_id is being displayed in this cell. T ...

What sets apart an object within the scalajs scope from the exact same object within the js.global scope?

Attempting to create a basic example for rendering a cube using the THREEJS library. package three import org.scalajs.dom import scala.scalajs.js import scala.scalajs.js.Dynamic._ import scala.scalajs.js.annotation.JSName ... object ThreeExample { d ...

AngularJS applies the active class to the button within a button group

Currently, I am facing an issue with a button group that consists of buttons, some created using HTML and others generated through ng-repeat. The goal is to have an active class applied to the button when clicked so that it can be customized to indicate th ...

End the response after sending with res.send() within the module

I am in the process of developing a module for validating requests that come through req.body. Instead of repeating the same code snippet in every server request, I aim to consolidate it into a single line within a module. const errors = validationResult( ...

Failed Socket.IO Cross-Origin Resource Sharing request

In the client-side code of my Angular module, I have the following setup for a socket client: angular.module('App') .factory('socketClient', function(socketFactory, Auth) { // Auto-configuring socket.io connection with authentic ...