【问题标题】:I am getting issue in changing inner HTML of div我在更改 div 的内部 HTML 时遇到问题
【发布时间】:2016-04-21 21:30:28
【问题描述】:

发现改变div的html有问题:

document.getElementsByClassName("lab")[0].setAttribute("ng-bind-html", "binds"); 
$scope.binds="<h1>run</h1>";

我在 java 脚本中设置属性 ng-bind-html,因为我已经在我的代码中集成了一些插件,其中 class="lab"div 是通过 JavaScript 声明的。属性binds 已正确附加,我在检查元素中检查了这一点。事实上,每当我在 JavaScript 中附加 ng-bind-html 的属性时,ng-bind-html 就不起作用。正确的方法是什么?代码没有错误。

【问题讨论】:

  • 我不是 Angular js 专家,但我知道它需要解析 html 属性才能设置事件处理。如果你有 JS 在这个解析发生后运行添加属性,angularjs 可能不知道它。如果是这种情况,您可以尝试通过以编程方式(使用 js)绑定元素而不是设置属性来修复它。

标签: javascript angularjs data-binding ng-bind-html angularjs-compile


【解决方案1】:

基本上,您已经动态添加了ng-bind-html 属性,这会将指令属性添加到DOM,但ng-bind-html 指令不会评估html 内容。您需要使用

重新编译该 DOM
$compile(document.getElementsByClassName("lab")[0])($scope)

为了确保这应该工作,您需要在您的 Angular 应用程序中添加 ngSanitize 模块。

Demo plunkr

您正在做的方式不是进行 DOM 操作的标准方式 在 AngularJS 中。标准方法是将 ng-bind-html 属性保留在 html 中,而不是动态添加。

标准方式

HTML

<h1>Cleaner way</h1>
<pre ng-bind-html="binds"></pre>

代码

(function(angular) {
  'use strict';
  angular.module('bindHtmlExample', ['ngSanitize'])
    .controller('ExampleController', ['$scope', '$compile', function($scope, $compile) {
      $scope.binds="<h1>run</h1>";

    }]);
})(window.angular);

Plunkr

【讨论】:

  • @AyyanAlvi 看看演示 plunkr,它会让你更好地了解如何在控制器函数中包含依赖项,基本上你需要在控制器函数的 $scope 参数旁边添加一个参数将它们分开与,
  • @AyyanAlvi 应该是app.controller('personCtrl', function($scope,$http,$sce, $compile) { $compile(document.getElementsByClassName("lab")[0])(scope); });
  • @AyyanAlvi 应该是$scope,我想你没有看更新的答案..
  • @AyyanAlvi 检查我附在答案中的 plunkr
  • @AyyanAlvi 很高兴为您提供帮助..谢谢 :)
猜你喜欢
  • 2023-01-18
  • 2019-12-05
  • 1970-01-01
  • 2015-01-20
  • 2011-09-26
  • 1970-01-01
  • 1970-01-01
  • 2011-12-23
  • 1970-01-01
相关资源
最近更新 更多