Access to dom in ng-repeat
Question about how to access dom elements inside ng-repeat directive in angular
HTML
<script src="https://code.angularjs.org/1.5.3/angular.js"></script>
<div ng-app="app">
<div ng-controller="myController as myCtrl">
<my-table list="myCtrl.list"></my-table>
</div>
</div>
JavaScript
// 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($timeout) {
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) {
// "p" element is accesible and we can change the color
var p = element[0].querySelector("p");
angular.element(p).css("color", "red");
// CANNOT FIND TR'S, the element tag contains <!-- ngRepeat: item in list -->
$timeout(function(){
var trs = element[0].querySelector("tr");
// ????????????????
console.log(trs);
});
}
return directive;
}
}());