我想在函数内的 Controller 中使用 $compile
,而不是在指令中。是否可以?我正在尝试下面的代码。
$compile('<div ng-attr-tooltip="test">Cancel</div>')(scope)
但这会抛出范围未定义的错误。我尝试在函数内传递 $scope
但它不起作用。
最佳答案
Angular 如何知道你更改了 DOM?您需要在附加 html 之前对其进行编译(使用 $compile 服务)。
如果您确实需要在指令之外进行访问,您可以创建一个注入(inject)器。
$(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));
});
});
关于javascript - 我们如何在 Angularjs 指令之外使用 $compile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22370390/