Utilizing Angular controllers to access data attribute values from child elements

Today I embarked on the journey of learning AngularJs through online tutorials. Excited about my new project, I started working on creating some useful features using Angular. Here is a snippet of my progress so far:

The HTML Part

<div data-ng-controller="DataGrid_Controller">
    <table class="table table-stripped">
        <thead>
            <tr>
                <th data-field="fname"> First Name </th>
                <th data-field="lname"> Last Name </th>
                <th data-field="email"> Email </th>
            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>
</div>

The Angular Part

<script type="text/javascript">
var app = angular.module('TestApp',[]);

app.controller('DataGrid_Controller', function($scope){
    //var fields = ['fname', 'lname', 'email']; 
    //How can I retrieve the value of data-field attributes within my Controller for further use?
})
</script>

Can someone guide me on how to access the values of data-attributes from child elements in my controller? Being a beginner in AngularJs, I am open to suggestions and corrections if I am approaching this problem incorrectly. Having experience with jQuery, I see a controller as a similar concept to a plugin. Any help in solving this issue would be greatly appreciated.

Answer №1

When working with Angular, it's important to focus on the model rather than the resulting DOM. The model serves as the source of truth, so headers should be included in the model. By looping through the data and matching each item with the headers, a table can be created. To accomplish this, you'll need a directive for manipulating the DOM, a controller for handling the data, and a simple template:

The DOM:

<div data-ng-controller="DataGrid">
  <table class="table table-striped">
    <thead>
      <tr>
        <th data-header="firstName" data-headers="headers">
          First name
        </th>
        <th data-header="lastName" data-headers="headers">
          Last name
        </th>
      </tr>
    </thead>
    <tbody>
      <tr data-ng-repeat="character in characters">
        <td data-ng-repeat="header in headers">
          {{character[header]}}
        </td>
      </tr>
    </tbody>
  </table>
</div>

Angular application:

'use strict';

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

Datagrid controller:

'use strict';

DataAttributes.controller('DataGrid', ['$scope', function($scope){
    $scope.characters = [
        {
            'firstName' : 'Anakin',
            'lastName' : 'Skywalker',
            'email' : '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8beae5e5e2eecbffeaffe4e4e2a5e5ee">[email protected]</a>',
            'age' : 9
        },
        {
            'firstName' : 'Kos',
            'lastName' : 'Palpatine',
            'email' : '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="99eaf0fdf0ecead9fdf8ebf2eaf0fdfcebeab7faf6f4">[email protected]</a>',
            'age' : 60
        },
        {
            'firstName' : 'Jar',
            'lastName' : 'Jar',
            'email' : '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="44373031342d20...">',
            'age' : 23
        }
    ];

    $scope.headers = [];
}]);

And a directive:

'use strict';

DataAttributes.directive('header', [function(){
    return {
        'restrict' : 'A',
        'scope' : {
            'headers' : '='
        },
        'link' : function(scope, iElement, iAttrs){
            scope.headers.push(iAttrs['header']);
        }
    };
}]);

A plunkr has been created for experimentation.

To simplify, think of having pre-existing data (characters) that needs to be dynamically displayed in a table. The directive captures field names (header) which are then bound to the controller's scope. Using ngRepeat, these fields are iterated through to render rows for each character element. Simple and effective!

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

Unable to retrieve file from server

Apologies for the basic question, but I'm feeling a bit lost at the moment. I've been diving into learning JavaScript and decided to set up a page on the 00webhost site to experiment and run tests. Everything was going well until I hit a roadblo ...

Changing a "boolean bit array" to a numerical value using Typescript

Asking for help with converting a "boolean bit array" to a number: const array: boolean[] = [false, true, false, true]; // 0101 Any ideas on how to achieve the number 5 from this? Appreciate any suggestions. Thanks! ...

Display the block if the HTTP response in AngularJS is successful

There are 3 blocks displayed depending on a boolean value. <button ng-if="user.friendship == null" ng-click="requestFriendship(user.user.id)" class="button button-outline button-calm"> Invite as friend </button> <button ng-if="user.frie ...

What sets apart window.app=new Vue({}) versus const app = new Vue({}) when included in app.js within a Vue.js environment?

What exactly is the difference between using window.app and const app in main.js within Vue? import question from './components/Questions.vue'; Vue.http.headers.common['X-CSRF-TOKEN'] = window.Laravel.csrfToken; window.App = new Vue({ ...

"Uh-oh! Encountered a new unexpected runtime error. Can't seem

While working on my portfolio in Next.js, I encountered an issue. I added a header to display on all pages by placing it in _app.js without making any changes to _document.js. Here is the error message: Unhandled Runtime Error Error: No router instance fo ...

Accessing NgModel as a number in the Kendo DropDownList

Is it possible to have values of number type in my ngModel when using KendoDropDownList with items containing Id (number) and Name (string) in the datasource? Here is an example for reference: ...

The parent's height remains unaffected by the margins of its child element

My code snippet is concise: .parent{ box-sizing: border-box; } .child{ height: 100px; margin: 20px; background: red; } .a1{ background: green; } <!DOCTYPE html> <html> <head> </head> <body> ...

Can a website be designed to render consistently across all browsers without relying on a CSS reset?

Is it possible to create a website that renders well across all browsers without using CSS reset? Should CSS reset be used for websites of all sizes - small, one-page, large? Is it better to write all the CSS without a reset and only address necessary rend ...

What steps should I take with my Android PWA manifest and service workers?

I created a web application that I want to prompt Android users to download when they visit. To build my service workers and manifest, I utilized PWA Builder which can be found at Now that I have the manifest file ready, should I simply upload it to the r ...

MongoDB facing difficulties in updating the database

Seeking help with my MongoDB setup as I am still new to it. I have a database where card data is stored and need to update counts when users like cards, resulting in a total likes number. I'm facing an issue where I keep getting a 400 error response ...

Tips for adjusting the autocomplete maxitem dynamically

I am working on a multi autocomplete feature and I have the following code. Is there a way to dynamically set the maximum number of items based on the value entered in another text field? <script> $(function () { var url2 = "<?php echo SI ...

Assign a value to an element based on a specific attribute value

I'm working with the following element <input type="text" size="4" name="nightly" value="-1"> My goal is to update the value to 15.9 specifically when name="nightly" Here's what I've attempted so far: document.getElementsByName(&ap ...

Developing interactive checkboxes for individual rows through React.js

Within a form, I have rows containing two inputs each. Upon clicking "add", a new row is created. For the second row onwards, by clicking "add" a checkbox labeled 1 should be added to indicate dependency on the previous row. In addition, for the third row, ...

ContainerView: challenges encountered when dynamically inserting views

ContainerView.pushObject() does not automatically connect dynamically added views with a Container object. The absence of an auto-wired container leads to a rendering error when a view renders a template containing a handlebars render helper. SIMPLE SCENA ...

"Enhancing the user experience: Triggering a window resize event in jQuery before page load on Magento

I am trying to trigger this function before the page finishes loading, but currently it only triggers after the page has loaded. Can anyone assist with this issue? $(window).on('load resize', function(){ var win = $(this); //this = window ...

On the same line, there are two divs with different characteristics - one dynamically changing width and the

I am facing an issue with arranging two divs under one parent div. The parent div is set to have a width of 100%: <div id="parent"> <div class="left"></div> <div class="right"></div> </div> The specific conditions ...

looping through the elements in a collection using a for-in loop

Issue with IE 11 Console Chrome Console Behavior When changing the word 'item' to 'anotherItem' in the loop like so: var obj = { id1: 'item 1', id2: 'item 2', id3: 'item 3' }; for (anothe ...

Tips for centering the InputLabel in Material UI?

Upon loading the page, I am looking to have the InputLabel appear as shown in the second picture. However, I haven't been able to find any InputLabel props that achieve this. I attempted using the focused prop, but it didn't give me the desired o ...

Is it possible to iterate through HTML form data using JSON arrays or objects?

I've been searching this website and the internet for a while now, trying to figure out how to save multiple arrays to my localStorage. I asked a question earlier which helped me progress a bit, but I'm still struggling to grasp the concept. I c ...

What is the process for modifying the user agent?

I'm struggling with phantom, the node.js wrapper for phantomjs. This is the approach needed in native phantomjs. page.settings.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/5 ...