【问题标题】:Is there a callback for ng-bind-html-unsafe in AngularJSAngularJS 中是否有 ng-bind-html-unsafe 的回调
【发布时间】:2014-02-05 22:27:47
【问题描述】:

我想删除一些由此带入 DOM 的元素...

<div ng-bind-html-unsafe="whatever"></div>

我写了一个可以删除元素的函数,但是我需要在ng-bind-html-unsafe 完成后触发该函数。是否有ng-bind-html-unsafe 的回调或更好的方法?

【问题讨论】:

    标签: javascript angularjs callback angularjs-directive


    【解决方案1】:

    ng-bind-html-unsafe 已从 angular 的当前版本 (1.2+) 中删除。我建议在新版本的 angular 中使用 $sanitize 服务。您需要包含 sanitize 库并将其添加到您的模块中。

    这样,一旦清理操作完成,您就可以做任何您想做的事情,而不必担心回调。

    快速而肮脏的实现:

    <!doctype html>
    <html lang="en">
    <head>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular.js"></script>
      <script src="libs/angular/angular-sanitize.js"></script>
    </head>
    <body ng-app="myApp">
      <div ng-controller="myController">
        <div>{{sanitized}}</div>
      </div>
      <script>
        angular.module('myApp', ['ngSanitize'])
          .controller('myController', ['$scope', '$sanitize', function($scope, $sanitize) {
            $scope.sanitized = $sanitize('someTextFromSomeSource');
            // Do whatever you want here with the cleaned up text
          }])
      </script>
    </body>
    </html> 
    

    【讨论】:

      【解决方案2】:

      我会将您演示中的 html 移动到 directive:

      <div ng-bind-html-unsafe="whatever"></div>
      

      在指令中,我将根据自己的需要操作 html,我在这里基于一个假设,因为我不确定 whatever 变量的更新频率或方式,因此通用解决方案将是 $watch像这样监听这个变量:

      $scope.$watch('whatever',function(newValue,oldValue, scope){
           //do something
      });
      

      我的新指令中的所有这些代码,可能你会想要使用postLink 函数

      这里是the Documentation from Angular 关于这个。

      后链接功能 在子元素链接后执行。在post-linking函数中做DOM转换是安全的。

      【讨论】:

      • 内容是静态的,但包含对外部 CSS 文件的引用。我正在尝试删除这些引用,例如... querySelectorAll('[rel="stylesheet"]') 所以我只需要在第一次加载后知道。
      • 您不要在控制器中操作 html,这不是正确的做法,该指令具有您所需要的。这是angular中推荐的。
      • 指令会在ng-bind-html-unsafe完成之前还是之后在元素上执行?
      • 这是一个 plunker 演示:plnkr.co/edit/c8WVtojWGVRAyEu0iLuW?p=preview 尝试使用您的代码对其进行扩展,它会让我们更好地了解如何为您提供帮助
      猜你喜欢
      • 1970-01-01
      • 2013-09-26
      • 1970-01-01
      • 1970-01-01
      • 2013-06-18
      • 1970-01-01
      • 1970-01-01
      • 2013-10-25
      • 1970-01-01
      相关资源
      最近更新 更多