9

我正在尝试学习 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);
}

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

帮助!

4

2 回答 2

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

              })
            }
          };
        });
于 2013-06-04T10:43:01.617 回答
6

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

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

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

如果没有,您可能只需将 $compile 注入控制器/指令/服务。

于 2013-06-03T23:45:46.470 回答