AngularJS ng-bind-html似乎没有更新DOM

AngularJS ng-bind-html does not appear to be updating the DOM

本文关键字:更新 DOM ng-bind-html AngularJS      更新时间:2023-09-26

这是正在发生的事情的一个基本示例。HTML绑定实际上工作得很好。我甚至可以在$scope.testDocument上发出警报,并获取我最新更新的内容。但是,如果我尝试选择使用该指令绑定的任何新插入的HTML元素,它总是返回0长度。是否存在jQuery需要的与我缺少的DOM的某种关系?

HTML代码段

<form>
    <button id="myButton" type="button" ng-click="testUpdate()">Test Update</button>
</form>
<div ng-bind-html="testDocument" id="testDocument"></div>

JavaScript代码段

$scope.testDocument = $sce.trustAsHtml("<div>My HTML.</div>");
$scope.testUpdate = function() {
    $scope.testDocument = $sce.trustAsHtml("<div><span class='test-new-element'>My HTML.</span></div>");
    alert($(".test-new-element").length);
}

编辑

我想在下面dave的回复后添加一些额外的细节。在更新绑定元素后,我添加了一个$watch,它似乎正在工作并做我想做的事情:

$scope.$watch(
    function() {
        return testDocument ;
    },
    function(newValue, oldValue) {
        if (newValue === oldValue) {
            alert($(".test-new-element").length); // Equals 1 as expected.
        }
    }
);

我阅读的有关此主题的文档可以在https://docs.angularjs.org/api/ng/type/$rootScope.Scope,并通过阅读$watch函数。

您需要等待角度摘要周期完成,直到完成为止,DOM尚未更新。最简单的(尽管有些技巧)解决方案是将其封装在$timeout:中

$timeout(function() { alert($(".test-new-element").length); });