Angular - Accessing the DOM element from a newly loaded template

I just started Angular last week, and I'm struggling to access the DOM from a freshly loaded template. Here's what happens -

index.html

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

Templates / top.html

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

app.js

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 cannot access dynamic elements from top.html , which is later loaded into the DOM with ng-repeat. Please let me know how to solve this. Thank!

Plunker - http://plnkr.co/edit/rRRRkJ20bm00yqslMtnS?p=preview

+4
source share
3 answers

This problem usually occurs when an event is fired before the DOM is updated.

DOM $timeout:

$timeout(function() {
    console.debug($("#myDiv"));
});

$timeout angular DOM, .

Edit: plunkr: http://plnkr.co/edit/TCTPZcAd2Lnrd6c4dMyx?p=preview

0

$scope.template_url = 'templates/top.html' , ng-click, , , .
, top.html .

$scope.template_url = 'templates/top.html';

<div class="template">
   <div ng-include="template_url"></div>
</div>

, , , $scope.

0

Source: https://habr.com/ru/post/1652567/


All Articles