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

时间:2014-03-13 06:07:32

标签: javascript angularjs

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

$compile('<div ng-attr-tooltip="test">Cancel</div>')(scope)

但这是抛出范围是未定义的错误。我试图在函数内部传递$scope,但它无效。

5 个答案:

答案 0 :(得分: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));
  });
});

答案 1 :(得分:11)

值得注意的是,上一个答案(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));
  });
});

参见documentation中的最后一段。

答案 2 :(得分: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);
  });
});

答案 3 :(得分:1)

我做了这个

var SCOPE;
app_module.controller('appController', function ($scope, $compile) {
    SCOPE = $scope;
    $scope.compile = function (elem_from, elem_to) {
        var content = $compile(angular.element(elem_from))($scope);
        angular.element(elem_to).append(content);
    }
});

像这样使用

SCOPE.compile(elem1.content, elem2);

答案 4 :(得分:1)

当我需要重新编译我的html以在页面上应用更改时,我按以下方式重新编译了我的html。

当我试图转到其他链接并再次返回页面时会发生这种情况,但出于某种原因,角度代码没有编译。

所以我通过在加载事件中再次编译页面的html部分来解决这个问题。

function OnLoad() {
angular.element("form:first").injector().invoke(['$compile', function ($compile) {
    var $scope = angular.element("form:first").scope();
    $compile("form:first")($scope);
}]);
}

以下是应用声明。

<form ng-app="formioApp" ng-controller="formioAppCtrl">

和OnLoad()函数在该页面上的html元素的onload事件中分配。