Manipulate the DOM elements within the ng-repeat directive

Hello, I am currently new to AngularJS and have just begun learning how to create directives.

While working on a sample project, I encountered an issue with accessing DOM elements rendered inside my directive. Some elements were not accessible in the link function because they had not been rendered yet.

Could someone please advise me on how to access these elements using ng-repeat and directives?

In my project, I was able to change the color of the "p" element, but I struggled to access and modify the properties of td's such as CSS styles or event bindings.

HTML

<div ng-app="app">
    <div ng-controller="myController as myCtrl">        
        <my-table list="myCtrl.list"></my-table>
    </div>
</div>

JS

// Main module
(function() {
    var app = angular.module("app", []);
}());

// Controller
(function() {
    angular.module("app")
        .controller("myController", myController);

    function myController() {
        var vm = this;
        vm.list = [
            { id: 1, name: "Alan" },
            { id: 2, name: "Jasmine" }
        ];
    }
}());

// Directive
(function() {
    angular.module("app")
        .directive("myTable", myTable);

    function myTable() {
        var directive = {
            link: link,
            replace: true,
            restrict: "E",
            scope: {
                list: "="
            },
            template: "<div>" +
                          "<p>My Table</p>" +
                          "<table>" +
                              "<tr ng-repeat='item in list'>" +
                                 "<td>{{item.id}}</td>" +
                                 "<td>{{item.name}}</td>" +
                              "</tr>" +
                          "</table>" +
                      "</div>"
        };

        function link(scope, element, attrs) {
            // Accessing and changing the color of the "p" element is successful
            var p = element[0].querySelector("p");
            angular.element(p).css("color",  "red");

            // Unable to find TRs, the element tag contains <!-- ngRepeat: item in list -->
            var trs = element[0].querySelector("tr");
            // ????????????????
        }

        return directive;
    }
}());

https://jsfiddle.net/hkhvq1hn/

I would greatly appreciate any help or suggestions. Thank you!

Answer №1

Is it possible to use $timeout to access the DOM after it has been rendered?

function link(scope, element, attrs) {
            // Access the "p" element and change its color to red
            var p = element[0].querySelector("p");
            angular.element(p).css("color",  "red");

            // Use $timeout to access DOM after rendering -->
            $timeout(function(){
                var trs = element[0].querySelector("tr");
                console.log(trs); 
            });

    }

View the updated fiddle

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

Customizing the input placeholder for password fields in IE8 using jQuery

Currently, I have opted to use jQuery instead of the HTML5 placeholder attribute <input type="text" name="email" value="Email" onfocus="if (this.value == 'Email') { this.value = ''; }" onblur="if (this.value == '') { this. ...

The TypeScript compiler is searching in an external directory for the node_modules folder

My angular 2 project is located in the directory /c/users/batcave/first_project. In that same directory, I have various files such as index.html, systemjs.config.js etc., and a node_modules folder that only contains @types and typescript. This means my @a ...

Ways to verify AJAX Response String when data format is specified as JSON

When using AJAX to retrieve JSON data from a webpage, it's essential to set the responseType to json. If the data processing is successful, a valid JSON string is returned, which works perfectly. However, if there's an error on the webpage, inst ...

What is the best way to send a string parameter from an Angular UI to a Node.js backend?

My goal is to transfer a string value from an Angular UI to a Node.js backend API, which will then search in MongoDB using the provided string value as shown below. I am attempting to receive input in enteredValue and pass it on to the http.get call as pa ...

Is there something I'm overlooking when it comes to vue router transitions?

I am attempting to implement a smooth transition between my Vue components with the following code: <template> <div id="app"> <router-link to="/">Go to home</router-link> <router-link to="Register">Go to register< ...

What is the process for invoking a function in ng-repeat after an object has been altered?

I am facing an issue with the following code snippet: <ul class="list-group" ng-init="curMarks=getTaskVotesModalInfo(task)"> <li ng-repeat="info in curMarks" class="list-group-item"> <span>{{info.worker}}</span> <span ...

What is the best way to replace multiple strings with bold formatting in JavaScript without losing the previous bolded text?

function boldKeywords(inputString, keywords){ for (var i = 0; i < keywords.length; i++) { var key = keywords[i]; if (key) inputString= inputString.replace(new RegExp(key, 'gi'), '<strong>' + ...

Tips for retrieving JSON data from an AJAX call and displaying it pre-filled in an input field

Here is the code snippet I used to receive a response in JSON format, but when I try to display the response using alert(response.Subject);, it shows as "undefined". HTML: <input type="text" id="subject" value='Subject'> Javascript: $.a ...

Ways to verify if a Discord.js snowflake is present in a collection of other identification numbers

I'm currently developing a Discord.js bot and I want to create a system where only specific IDs listed in a JSON file can trigger certain commands. However, I'm unsure about how to implement this logic within an if statement. if (message.author. ...

Utilize React hooks to efficiently filter multiple JSON requests

I am currently working on creating a filter system that can combine multiple filters for users to choose from, such as "big/not-big" and "heavy/not-heavy". Each filter corresponds to loading a JSON file. My goal is to merge the results of these JSON files ...

Tips for minimizing the size of this script

I am new to using Jquery and Javascript, but I have managed to create a script that communicates with a php controller in symfony2. My query is, how can I shorten the script length? Is there a more efficient way to solve the logic instead of using the swi ...

Experiencing an issue with the countdown timer while utilizing react-countdown library

Currently, I am in the process of creating a countdown timer that allows users to input time in minutes and start or stop the clock. However, I have encountered two challenges: I defined a state running to determine if the clock is running, and based on t ...

Is it possible to create a collapse and expand animation that does not involve transitioning the `height

After extensively researching, I have come across numerous articles advocating for the use of transform and opacity for achieving smooth CSS transitions. An example can be found here: The prevailing notion always revolves around: ...the optimization ...

Different methods for dynamically altering the style attribute

Here's some code I wrote: <html> <head> <style> .containerTitle { background-color:silver; text-align:center; font-family:'Segoe UI'; font-size:18px; font-weight:bold; height:30px; } ...

How to divide and access a particular cell in Angular?

I am working with an object called flight.flight_number. Within this object, flight.flight_number is set to: a11;g73;jb87;dd45; The flight.flight_name values are London;Berlin;Torino;Rome; Each value is separated by ';' Here is the code I hav ...

Make sure to always display the status bar and soft keys

Is there a way to set up my ionic app on Android so that the status bar is always displayed at the top and the soft keys are shown at the bottom? I attempted to add this line to the config.xml file, but it didn't work. <preference name="Fullscree ...

Using the OR Operator with a different function in React

Struggling with setting the day flexibility using disableDate(1,2,3,4,0) but it's not functioning as expected. Can you assist me in fixing this issue? Here is the function snippet: const disableDate = (date) => { const day = date.day(); retur ...

I encountered an issue with the "props map error" while working on this

Hello everyone, I am currently in the process of learning React by creating a toggle button for switching between light and dark modes. However, I have encountered an issue when attempting to map through the state and display the data in card format (altho ...

Ensure that when adjusting the height of a div, the content is always pushed down without affecting the overall layout of the page

My webpage contains a div element positioned in the middle of the content, with its height being adjustable through JavaScript code. I am seeking a way to manage the scrolling behavior when the height of the div changes. Specifically, I want the content t ...

What could be the reason behind the error message 'No Bower components found' when running 'grunt serve'?

Starting an Angular app using angular-fullstack on my Windows 7 machine has been a bit of a challenge. I installed several npm packages globally, including grunt-bower-install. To create the application, I used the following command: yo angular-fullstac ...