我们如何在Angularjs中的指令之外使用$ compile

use*_*394 22 javascript angularjs

我想$compile在函数内部的控制器中使用而不是在指令中使用.可能吗?我正在尝试下面的代码.

$compile('<div ng-attr-tooltip="test">Cancel</div>')(scope)
Run Code Online (Sandbox Code Playgroud)

但这是投掷范围是未定义的错误.我试图传递$scope函数内部,但它无法正常工作.

Vai*_*ain 20

Angular如何知道你改变了DOM?你需要在附加它之前编译你的html(使用$ compile服务).

如果您绝对需要在指令之外访问,则可以创建注入器.

$(function() {
  // myApp for test directive to work, ng for $compile
  var $injector = angular.injector(['ng', 'myApp']);
  $injector.invoke(function($rootScope, $compile) {
    $('body').prepend($compile('<div ng-attr-tooltip="test">Cancel</div>')($rootScope));
  });
});
Run Code Online (Sandbox Code Playgroud)


idm*_*tme 11

值得注意的是,前面的answer(var $injector = angular.injector(['ng', 'myApp']);)中的注入器不会将编译指令附加到当前运行的角度应用程序,它将创建新的.

要动态地将新指令附加到您的应用程序,您应该使用已存在的注入器:

$(function() {
  angular.element(document).injector().invoke(function($rootScope, $compile) {
    $('body').prepend($compile('<div ng-attr-tooltip="test">Cancel</div>')($rootScope));
  });
});
Run Code Online (Sandbox Code Playgroud)

文件的最后一段.


Jos*_*rns 5

我试过@Vaibhav Jain的回答,没有成功.经过一番挖掘,这是我发现在Angular 1.3和jQuery上工作的东西:

$(function() {
  angular.element(document).injector().invoke(['$compile', function ($compile) {
    // Create a scope.
    var $scope = angular.element(document.body).scope();
    // Specify what it is we'll be compiling.
    var to_compile = '<div ng-attr-tooltip="test">Cancel</div>';
    // Compile the tag, retrieving the compiled output.
    var $compiled = $compile(to_compile)($scope);
    // Ensure the scope and been signalled to digest our data.
    $scope.$digest();
    // Append the compiled output to the page.
    $compiled.appendTo(document.body);
  });
});
Run Code Online (Sandbox Code Playgroud)