skos skos - 1 year ago 64
AngularJS Question

Angular - Access DOM Element From Just Loaded Template

I just started Angular last week and I am struggling to access DOM from a template thats just loaded. Here's whats happening -


<div class="template" ng-app="myApp" ng-controller="myController">
<div ng-include="template_url"></div>
<input type="button" value="Load Top" ng-click="loadTopTemplate()">


<li ng-repeat="(key, myObjectItem) in myObject">
<span id="{{key}}">{{myObjectItem | uppercase}}</span>
<span id="staticElement">Static Element</span>


var app = angular.module('myApp', []);
app.controller('myController', function($scope) {
$scope.myObject = {"item1": "one", "item2": "two", "item3": "three", "item4": "four", "item5": "five"};
$scope.loadTopTemplate = function() {
$scope.template_url = 'top.html';

$scope.$on('$includeContentLoaded', function() {
console.debug("template loaded");
console.debug("Static element text: " + document.getElementById("staticElement").innerHTML); //works
console.debug("Dynamic element text: " + document.getElementById("item5").innerHTML); //doesn't work

I am not able to access dynamic elements from top.html which gets loaded in DOM later on using
. Please let me know how to resolve this. Thanks!

Plunker -

Answer Source

Usually this issue occurs when the event is fired before the DOM is updated.

A common solution is to wrap your access to the DOM in a $timeout:

$timeout(function() {

$timeout without a delay will let angular finish the digest-cycle and update the DOM before trying to access it.

Edit: Here is your modified plunkr:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download