javascript - 如何从 Angular 之外编译动态模板?

标签 javascript angularjs

我想通过 AJAX 加载动态 HTML 内容,然后编译它,因为它包含 Angular Directive(指令)。

我有this class它使用有助于使用 Angular 方法,但不在 Angular Controller 或指令的范围内:

var AngularHelper = (function () {
    var AngularHelper = function () { };

    /**
     * ApplicationName : Default application name for the helper
     */
    var defaultApplicationName = "MyApp";

    /**
         * Compile : Compile html with the rootScope of an application
         *  and replace the content of a target element with the compiled html
         * @$targetDom : The dom in which the compiled html should be placed
         * @htmlToCompile : The html to compile using angular
         * @applicationName : (Optionnal) The name of the application (use the default one if empty)
         */
    AngularHelper.Compile = function ($targetDom, htmlToCompile, applicationName) {
        var $injector = angular.injector(["ng", applicationName || defaultApplicationName]);

        $injector.invoke(["$compile", "$rootScope", function ($compile, $rootScope) {
                        //Get the scope of the target, use the rootScope if it does not exists
            var $scope = $targetDom.html(htmlToCompile).scope();
            $compile($targetDom)($scope || $rootScope);
            $rootScope.$digest();
        }]);
    }
    return AngularHelper;
})();

然后我在 jQuery 成功的 ajax 请求后使用它:

<!DOCTYPE html>
<html>
    <head>
        <title>AngularJS Test</title>
    </head>
    <body>
        <div id="contents"><!-- content --></div>
        <script src="js/angular.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                $.get( "http://fuiba.com/test/index.html", function( data ) {
                    $("#result").html(data);
                    AngularHelper.Compile('$("#result")', data);
                });
            });
        </script>
    </body>
</html>

但我收到此错误(参见 codepen ):

$targetDom.html is not a function

最佳答案

您需要传递一个 DOM 元素而不是字符串作为 AngularHelper.Compile 函数中的第一个参数,

所以

AngularHelper.Compile($("#result"), data);

不是

AngularHelper.Compile('$("#result")', data);

关于javascript - 如何从 Angular 之外编译动态模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36286193/

相关文章:

javascript - AngularJS Jasmine 测试: scoped variable always undefined

AngularJS : Extending built-in filters

javascript - 如何不在 Angular 中使用 'this'?

javascript - jQuery Mobile 多重过滤方法 - 文本/输入和选择/下拉菜单

javascript - 保存后JavaScript中的隐藏字符

javascript - 为每个 mysql 创建用 javascript 提交

javascript - 在 ng-repeat 语句中按子数组过滤对象,该语句使用 track by $index 来处理重复

javascript - 在 AngularJS 场景中向 Froala 编辑器添加自定义下拉菜单

Javascript/Html 如何使用下拉框禁用下拉框

javascript - 使用 ES6 制作迭代器