AngularJS - 编译来自数据库的动态HTML字符串 [英] AngularJS - Compiling dynamic HTML strings from database

查看:229
本文介绍了AngularJS - 编译来自数据库的动态HTML字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的角应用程序中嵌套一个叫做Page指令,由控制器的支持,其中包含一个div的NG-绑定-HTML不安全的属性。这被分配到名为pageContent一$范围变种。该变种会从数据库中动态分配生成的HTML。当用户翻转到下一个页面,一个叫做到数据库被造的,pageContent var设置这个新的HTML,这将会通过NG-绑定-HTML不安全的屏幕上呈现。这里的code:

Nested within our Angular app is a directive called Page, backed by a controller, which contains a div with an ng-bind-html-unsafe attribute. This is assigned to a $scope var called 'pageContent'. This var gets assigned dynamically generated HTML from a database. When the user flips to the next page, a called to the DB is made, and the pageContent var is set to this new HTML, which gets rendered onscreen through ng-bind-html-unsafe. Here's the code:

Page指令

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即可)

Page directive's template ("page.html" from the templateUrl property above)

<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浏览器很好地呈现。当用户翻转到下一个页面,我们看到了下一个页面的内容,等等。到目前为止好。

That works. We see the page's HTML from the DB rendered nicely in the browser. When the user flips to the next page, we see the next page's content, and so on. So far so good.

这里的问题是,我们希望有一个页面内容的内部互动内容。例如,HTML可以包含一个缩略图,其中,当用户点击它,角应该做的事真棒,如显示弹出模式窗口。我已经放在角方法调用(NG-点击)在我们的数据库中的HTML字符串,但当然棱角分明是不会承认任何一种方法调用或指令,除非它以某种方式解析HTML字符串,识别它们并编译他们。

The problem here is that we want to have interactive content inside of a page's content. For instance, the HTML may contain a thumbnail image where, when the user clicks on it, Angular should do something awesome, such as displaying a pop-up modal window. I've placed Angular method calls (ng-click) in the HTML strings in our database, but of course Angular isn't going to recognize either method calls or directives unless it somehow parses the HTML string, recognizes them and compiles them.

在我们的数据库

内容第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>

早在页面控制器,我们再添加相应的$范围功能:

Back in the Page controller, we then add the corresponding $scope function:

页控制器

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

我无法弄清楚如何调用'doSomethingAwesome'方法从DB HTML字符串中。我意识到角以某种方式解析HTML字符串,但如何?我读过模糊mumblings有关$编译服务,复制和粘贴的一些例子,但没有任何工程。此外,大多数的例子显示动态内容在指令的链接阶段才刚刚成立。我们希望页在整个应用程序生命活路。它不断地接收,汇总和用户翻阅页面显示新的内容。

I can't figure out how to call that 'doSomethingAwesome' method from within the HTML string from the DB. I realize Angular has to parse the HTML string somehow, but how? I've read vague mumblings about the $compile service, and copied and pasted some examples, but nothing works. Also, most examples show dynamic content only getting set during the linking phase of the directive. We would want Page to stay alive throughout the life of the app. It constantly receives, compiles and displays new content as the user flips through pages.

在抽象意义上,我想你可以说我们正在尝试的一个角角应用程序中动态地窝块,需要能够交换他们进出。

In an abstract sense, I guess you could say we are trying to dynamically nest chunks of Angular within an Angular app, and need to be able to swap them in and out.

我读过角文档多次的各个位,以及各种博客文章,和JS拨弄着人们的code。我不知道我是否完全误解角,或者只是简单的东西,或者也许我慢。在任何情况下,我可以使用一些建议。

I've read various bits of Angular documentation multiple times, as well as all sorts of blog posts, and JS Fiddled with people's code. I don't know whether I'm completely misunderstanding Angular, or just missing something simple, or maybe I'm slow. In any case, I could use some advice.

推荐答案

NG-结合HTML的不安全只呈现内容为HTML。它不绑定角度范围,所得DOM。你必须使用 $编译服务用于这一目的。我创建这plunker 来演示如何使用 $编译来创建指令使用户输入和绑定到控制器的范围动态HTML。源发布如下。

ng-bind-html-unsafe only renders the content as HTML. It doesn't bind Angular scope to the resulted DOM. You have to use $compile service for that purpose. I created this plunker to demonstrate how to use $compile to create a directive rendering dynamic HTML entered by users and binding to the controller's scope. The source is posted below.

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>';
}

这篇关于AngularJS - 编译来自数据库的动态HTML字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆