Justin Justin - 4 months ago 20
AngularJS Question

get html elements in angularJS

I am new in AngularJS world. I have a circumstance here.

<!DOCTYPE html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp">

<table ng-controller="myCtrl" border="1">
<tr class="x" ng-repeat="x in records">

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.records = [
"Name" : "Alfreds Futterkiste",
"Country" : "Germany"
"Name" : "Berglunds snabbköp",
"Country" : "Sweden"
"Name" : "Centro comercial Moctezuma",
"Country" : "Mexico"
"Name" : "Ernst Handel",
"Country" : "Austria"
var arrays = document.getElementsByClassName("x");

I tried to get the array of html elements I did load by angularJS (using ng-repeat). When I logged the value of whole array, its results are correct. However when I logged the array.length or array[1], the results are 0 and undefined respectively. I tried to put these code in $scope.on('viewContentLoaded') to ensure that all html elements finished loading, but the results are the same. So what is my stupidity here?

Thank you.


One thing to remember, is that angular is doing certain things async. When meaning, that when you assign your records in your controller, angular will only start rendering after your controller method is completed. Hence, your request for elements of the document will return nothing.

One way to go around it in certain cases is to use $timeout service.

 var arrays = document.getElementsByClassName("x");

The method within timeout should be executed when the angular digest cycle is done rendering.