我们如何在 Angularjs 中的指令之外使用 $compile [英] how can we use $compile outside a directive in Angularjs
本文介绍了我们如何在 Angularjs 中的指令之外使用 $compile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在函数内部的控制器中使用 $compile
而不是在指令中.是否可以?我正在尝试下面的代码.
$compile('Cancel')(scope)
但这是抛出范围未定义的错误.我试图在函数内部传递 $scope
但它不起作用.
解决方案
Angular 如何知道您更改了 DOM?您需要在附加之前编译您的 html(使用 $compile 服务).
如果你绝对需要指令之外的访问,你可以创建一个注入器.
$(function() {//myApp 用于测试指令工作,ng 用于 $compilevar $injector = angular.injector(['ng', 'myApp']);$injector.invoke(function($rootScope, $compile) {$('body').prepend($compile('<div ng-attr-tooltip="test">Cancel</div>')($rootScope));});});
I want to use $compile
in a controller inside a function and not in a directive. is it possible? I am trying the below code.
$compile('<div ng-attr-tooltip="test">Cancel</div>')(scope)
But this is throwing scope is undefined error. I tried to pass $scope
inside the function but it is not working.
解决方案
How would Angular know that you changed the DOM? You need to compile your html before appending it (using $compile service).
If you absolutely need access outside of a directive you can create an injector.
$(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));
});
});
这篇关于我们如何在 Angularjs 中的指令之外使用 $compile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文