天天看点

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”)

...

...

页面控制器

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页的内容:

Here's a cool pic of a lion.

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

Click on him to see a large image.

第2页的内容:

Here's a snake.

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

Click to make him hiss.

回到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,还是只是错过了一些简单的东西,或者我很慢。无论如何,我可以使用一些建议。