angularJS $ compile未定义

use*_*052 9 angularjs

我正在尝试学习AngularJS,我正在尝试动态编译一些DOM元素......我尝试过这个演示:

try {
        var templateHTML = angular.element('<p>{{total}}</p>'),
            scope = ....;

        var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) {
          //attach the clone to DOM document at the right place
        });

        //now we have reference to the cloned DOM via `clone`
} catch (ex) {
alert(ex.message);
}
Run Code Online (Sandbox Code Playgroud)

但我得到的只是"$ compile未定义"

救命!

小智 8

在指令中使用$ compile的示例代码.基本上继续&首先将元素附加到DOM(可能希望保持不可见),然后使用finder运行编译..如rtcherry所提到的,应该注入$ compile.

        //
        componentModule.directive('getCompilerWk', function($compile) {
          return {
            restrict: 'A',
            link: function(scope, elm, attr) {
              elm.click(function(){
                    $(body).append(templateHTML);
                    $compile($(body).find('p'))(scope);

              })
            }
          };
        });
Run Code Online (Sandbox Code Playgroud)


rtc*_*rry 6

你在哪里调用这段代码?通过使用angular.element(...)来假设它在Angular框架之外是否安全?

如果是这样,你可以使用这个:

// Split across two lines for readability...
angular.element(<something within Angular's scope>)
    .injector().get('$compile')(...)
Run Code Online (Sandbox Code Playgroud)

如果没有,您可能只需要将$ compile注入controller/directive/service.