sko*_*kos 5 javascript jquery angularjs
我上周刚刚开始使用Angular,我正在努力从刚加载的模板中访问DOM.这里发生了什么 -
的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>
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
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
});
});
Run Code Online (Sandbox Code Playgroud)
我无法访问top.html中的动态元素,后者在以后使用时会加载到DOM中ng-repeat.请让我知道如何解决这个问题.谢谢!
Plunker - http://plnkr.co/edit/rRRRkJ20bm00yqslMtnS?p=preview
通常,在更新 DOM 之前触发事件时会出现此问题。
一个常见的解决方案是将您对 DOM 的访问包装在 $timeout 中:
$timeout(function() {
console.debug($("#myDiv"));
});
Run Code Online (Sandbox Code Playgroud)
没有延迟的 $timeout 会让 Angular 完成摘要循环并在尝试访问 DOM 之前更新它。
编辑: 这是您修改后的plunkr:http://plnkr.co/edit/TCTPZcAd2Lnrd6c4dMyx ?p=preview