小编典典

从数据库编译动态HTML字符串

html

情况

嵌套在我们的Angular应用程序中的是一个称为Page的指令,该指令由控制器支持,该指令包含一个具有ng-bind-html-
unsafe属性的div。这被分配给名为“ pageContent”的$
scope变量。从数据库中为该变量分配动态生成的HTML。当用户跳至下一页时,将对数据库进行调用,并将pageContent
var设置为此新的HTML,并通过ng-bind-html-unsafe在屏幕上呈现。这是代码:

页面指​​令

angular.module('myApp.directives')
    .directive('myPage', function ($compile) {

        return {
            templateUrl: 'page.html',
            restrict: 'E',
            compile: function compile(element, attrs, transclude) {
                // does nothing currently
                return {
                    pre: function preLink(scope, element, attrs, controller) {
                        // does nothing currently
                    },
                    post: function postLink(scope, element, attrs, controller) {
                        // does nothing currently
                    }
                }
            }
        };
    });

Page指令的模板 (来自上面templateUrl属性的“ page.html”)

<div ng-controller="PageCtrl" >
   ...
   <!-- dynamic page content written into the div below -->
   <div ng-bind-html-unsafe="pageContent" >
   ...
</div>

页面控制器

angular.module('myApp')
  .controller('PageCtrl', function ($scope) {

        $scope.pageContent = '';

        $scope.$on( "receivedPageContent", function(event, args) {
            console.log( 'new page content received after DB call' );
            $scope.pageContent = args.htmlStrFromDB;
        });

});

那个有效。我们看到来自数据库的页面HTML在浏览器中呈现得很好。当用户切换到下一页时,我们会看到下一页的内容,依此类推。到目前为止,一切都很好。

问题

这里的问题是我们希望在页面内容中包含交互式内容。例如,HTML可能包含一个缩略图,当用户单击它时,Angular应该做一些很棒的事情,例如显示弹出的模式窗口。我已经在数据库的HTML字符串中放置了Angular方法调用(ng-
click),但是Angular当然不会识别方法调用或指令,除非它以某种方式解析HTML字符串,识别它们并进行编译。

在我们的数据库中

第1页的内容:

<p>Here's a cool pic of a lion. <img src="lion.png" ng-click="doSomethingAwesone('lion', 'showImage')" > Click on him to see a large image.</p>

第2页的内容:

<p>Here's a snake. <img src="snake.png" ng-click="doSomethingAwesone('snake', 'playSound')" >Click to make him hiss.</p>

回到Page控制器,然后添加相应的$ scope函数:

页面控制器

$scope.doSomethingAwesome = function( id, action ) {
    console.log( "Going to do " + action + " with "+ id );
}

我无法弄清楚如何从数据库的HTML字符串中调用“
doSomethingAwesome”方法。我意识到Angular必须以某种方式解析HTML字符串,但是如何?我已经读过有关$
compile服务的含糊不清的说法,并复制并粘贴了一些示例,但没有任何效果。同样,大多数示例都显示动态内容仅在指令的链接阶段设置。我们希望Page在应用程序的整个生命周期中保持活力。当用户翻阅页面时,它会不断接收,编译和显示新内容。

从抽象的意义上讲,我猜您可能会说我们正在尝试在Angular应用程序中动态嵌套Angular的块,并且需要能够将它们交换进出。

我已经多次阅读了Angular文档的各种内容,以及各种博客文章和JS
Fiddled的人的代码。我不知道我是完全误解了Angular,还是只是错过了一些简单的东西,或者我很慢。无论如何,我可以使用一些建议。


阅读 528

收藏
2020-05-10

共1个答案

小编典典

ng-bind-html-unsafe仅将内容呈现为HTML。它不会将Angular范围绑定到结果DOM。您必须$compile为此目的使用服务。我创建了这个插件,以演示如何用于$compile创建指令来呈现用户输入的动态HTML并将其绑定到控制器的作用域。来源发布在下面。

demo.html

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <script data-require="angular.js@1.0.7" data-semver="1.0.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Compile dynamic HTML</h1>
    <div ng-controller="MyController">
      <textarea ng-model="html"></textarea>
      <div dynamic="html"></div>
    </div>
  </body>

</html>

script.js

var app = angular.module('app', []);

app.directive('dynamic', function ($compile) {
  return {
    restrict: 'A',
    replace: true,
    link: function (scope, ele, attrs) {
      scope.$watch(attrs.dynamic, function(html) {
        ele.html(html);
        $compile(ele.contents())(scope);
      });
    }
  };
});

function MyController($scope) {
  $scope.click = function(arg) {
    alert('Clicked ' + arg);
  }
  $scope.html = '<a ng-click="click(1)" href="#">Click me</a>';
}
2020-05-10