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!