【问题标题】:How to compile dynamic template from outside of angular?如何从角度外部编译动态模板?
【发布时间】:2016-03-29 22:09:57
【问题描述】:

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

我有 this class 使用有助于使用 angular 的方法,而不是在 angular 控制器或指令的范围内:

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 不是函数

【问题讨论】:

  • 在这一行AngularHelper.Compile('$("#result")', data); 中,您正在为参数$targetDom 传递字符串('$("#result")'),但稍后在函数中,您可以通过调用.html 函数来处理它,就像处理jQuery 对象一样。 String 类当然没有这种方法。
  • @RytisAlekna 感谢您和 MiTa,问题已解决,但我遇到了另一个错误。看到这个codepen

标签: javascript angularjs


【解决方案1】:

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

所以

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

不是

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

【讨论】:

  • 非常感谢@MiTa!问题解决了,但我得到另一个错误:Module 'MyApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.codepen
  • 看第 41 行 angular.module('MyApp') 你只是得到这个模块,但你必须创建它 angular.module('MyApp',[])
  • 我不知道为什么这个 AngularHelper 类非常适合其他人而不适合我。我收到另一个错误:$targetDom.html(...).scope is not a function。我会努力解决的!谢谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-25
  • 2017-12-06
  • 1970-01-01
  • 1970-01-01
  • 2018-11-14
  • 1970-01-01
相关资源
最近更新 更多