检测在angular中传递给$compile的字符串的最佳方法是可编译的

Best way to detect that a string passed to $compile in angular is compile-able?

本文关键字:最佳 字符串 方法 编译 compile angular 检测      更新时间:2023-10-11

我正在构建一个接受"消息"的指令,该"消息"还可以包含html和嵌套的angular指令。现在,在我的指令的控制下,我做:

var compiled = $compile(message)($scope);
this.message = $sce.trustAsHtml(compiled.html());

但是,如果消息没有有效的开始和结束标记,它就不会编译。我想知道是否还有其他方法,或者angular是否有任何方法可以在不使用regex的情况下做到这一点。

我肯定不会解析或验证HTML。jQuery/jqLite已经为我们做到了。

angular.element需要一个根元素。因此,将您的消息封装在根元素中,编译并链接,然后取出内容:

link: function(scope, element){
    scope.param = "test";
    var message = "foo {{param}} bar";
    var el = angular.element("<div>").append(message);
    var compiled = $compile(el)(scope);
    element.append(compiled.contents());
}