Angular Directive - Embedding Complex Objects in Attribute

Here's a fantastic solution provided for this specific question, demonstrating how to utilize a directive to showcase nested objects as <tr>'s. However, I'm aiming to take it a step further by passing a nested object into my attribute as well.

In the case below, I've introduced obj to my scope and connected the rows directly to obj. Yet, upon doing so, it stops functioning and none of the rows are rendered. What could be causing this issue?

I suspect that there might be an issue with scope[attrs.rows] but I'm not entirely sure.

HTML:

<div ng-controller="MyCtrl">
    <my-table rows='obj.rows'></my-table>
</div>

Javascript:

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

myApp.directive('myTable', function () {
    return {
        restrict: 'E',
        link: function (scope, element, attrs) {
            var html = '<table>';
            angular.forEach(scope[attrs.rows], function (row, index) {
                html += '<tr><td>' + row.name + '</td></tr>';
                if ('subrows' in row) {
                    angular.forEach(row.subrows, function (subrow, index) {
                        html += '<tr><td>' + subrow.name + '</td></tr>';
                    })
                }
            })
            html += '</table>';
            element.replaceWith(html)
        }
    }
});

function MyCtrl($scope) {
    $scope.obj = {
        rows = [];
    }
    $scope.obj.rows = [
        { name: 'row1', subrows: [{ name: 'row1.1' }, { name: 'row1.2' }] },
        { name: 'row2' }
    ];
}

Link to fiddle: http://jsfiddle.net/mattheye/uqNLH/1/

I am striving to achieve functionality similar to this fiddle: http://jsfiddle.net/mrajcok/vGUsu/

Answer №1

When accessing the rows using scope[attrs.rows], it is recommended to use scope.$eval instead, as shown below:

angular.forEach(scope.$eval(attrs.rows), function (row, index) {

Try this Demo


Keep in mind that updating rows on MainCtrl will not automatically reflect here because the value is only read once.

To establish proper binding, consider setting up a $watch on attrs.rows like demonstrated here: http://jsfiddle.net/uqNLH/7/

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

Is there a way to integrate a snap carousel in a vertical orientation?

I am looking to make a List utilizing the snap carousel component, but I'm having trouble getting it set up. Can anyone help me with this? ...

Integrate Tailwind CSS into the bundled JavaScript file

Is there a way to integrate tailwind css into bundle js effectively? Take a look at this example involving vue 3 and tailwind 3 https://github.com/musashiM82/vue-webpack. Upon executing npm run build , it generates 3 files: app.js ABOUTPAGE.js app.6cba1 ...

unable to comprehend the remaining section

My divs are not checking/unchecking properly. The else part of my code is unable to read it and displays 'undefined'. Please assist me... (The first click works correctly but the second click shows 'undefined') import React, { useState ...

What is the correct way to chain promises within Promise.all?

Essentially, I retrieve all the rows from a schedule table and then process each individual row. If the row is already in the command table, I skip it. Otherwise, I insert it. Within Promise.all(rows.map(function(row){ I have 2 chained promises: return ...

Having trouble getting typeahead suggestions to display in Bootstrap UI when using AngularJS?

I am having trouble getting static suggestions to display in a search textbox. I have tried following the example at this link. Below is the code I am working with: Here is my HTML code: <div> <input type="text" name="questions" id="que ...

Is it possible to prevent users from clearing data in an Android application when using Ionic framework?

Currently, I am developing an app using the Ionic framework. The data is being stored on the mobile device via SQLite, but there is a concern that users can easily clear this data by clicking on the "clear data" button in the application info settings. The ...

I created a news platform using Next.js server-side rendering, but I'm having trouble with the export const metadata = { title: "TEST" } not functioning as intended

After building my News Website using Next.js with Server Side Rendering, I encountered an issue with setting the page title. Despite using export const metadata = { title: "TEST" }, the title remained unchanged. The metadata object appears to be ...

A step-by-step guide on extracting values from JSON using JavaScript

I am facing a challenge in extracting values from a JSON string. The JSON string I have is: {"user":{"id":"1","firstname":"Freelogin","created":"0000-00-00 00:00:00","lastname":"Administrator","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_ ...

Ways to discover the titles of every sub-directory

Suppose I have the absolute path of a directory. Is there a method in JavaScript (Node.js) to determine how many sub-directories it has, and retrieve the names of all its sub-directories? I searched online but didn't come across any solution. ...

Integrating Illumination into a ShaderMaterial in three.js

I'm exploring the idea of creating a ShaderMaterial with lighting similar to that of a MeshLambertMaterial. To achieve this, I have developed a vertex and fragment shader (available here) and included the uniforms from THREE.ShaderLib[ 'lambert&a ...

response cannot be generated outside of the db.query function

router.get('/details/(:id)', (req, res) => { let vehicle_base; db.query("select b.name, count(b.name) AS total_vehicles from base AS b, vehicle AS v where b.id = v.base_id AND b.fleet_id = " + req.params.id , function(err, result){ ...

Utilizing Jquery to wrap HTML content with div elements within a secure Content Management System

Despite my best efforts, I have hit a roadblock and need some help. I want to utilize Javascript/Jquery within this restrictive cms to wrap two lists in their own div. Take a look at the current code snippet below. Unfortunately, the closed cms is set in ...

Vue is struggling to load the component files

Lately, I've been encountering an error during webpack build that is causing some issues. ERROR There were 3 errors encountered while compiling The following relative modules could not be found: * ./components/component1.vue in ./resources/assets/ ...

Slick Slider fails to load on web browsers

Hi everyone, I have a snippet of HTML code that I need help with: <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/jquery.slick/1.6.0/slick.css"/> </head> <body> ...

Using jQuery to toggle the visibility of divs depending on the selection of multiple checkboxes

I found this code snippet that I need help with. <div class="row"> <div class="col-xs-4"> <label class="checkbox-inline"><input type="checkbox" value="draft">Draft</label> </div> <div class="c ...

Does anyone know if it's feasible to return a value from PHP to an HTML form without relying on JavaScript?

Currently, I am in the process of learning how to create a basic web form. My goal is to develop an HTML web form that sends a number to PHP and then displays the number in another text field without refreshing the page. After doing some research online, ...

Using jQuery to Decode the XML Document Containing National Threat Level Data

Recently, I've been experimenting with using jQuery to extract data from the DHS Threat Level found in their XML file. However, despite my efforts, I haven't been able to make it work. As a newcomer to Javascript and non-presentational jQuery, I& ...

Combine and calculate the total of several columns using the Loadash library

In my Vue application, I am faced with the challenge of grouping an array by date and then calculating sums for multiple columns. The current method I have only allows me to group and sum one column: receiptsByDate: function(){ let byDate = _.groupBy(t ...

When double quotes are used in a string within an HTML input field, they may display as &

Using PHP, I am retrieving data from an SQL database and generating JavaScript code to create an edit button for each entry. The edit button triggers a text input field within a form. When the user clicks on the generated edit button, the text in this inpu ...

The issue of nested form serialization not functioning properly in JQuery has been identified

I am currently in the process of developing a web application. One particular page within this application contains a form, called form1, and I am inserting another page with its own form, form2, inside of form1. Each form contains their own set of values. ...