你为什么在角度外调用jquery?通常情况下,你会从一个角度指令中做一些事情,例如可以访问$ compile。如果你绝对需要外部访问,你可以创建一个注入器。 (PLUNKER)
angular.module('myApp', []).directive('test', function($compile) {
return {
restrict: 'E',
link: function(scope, element, attributes) {
$(element).html('<h1>this is a test!</h1>')
}
}
});
///////////////////////////////////////////////////////////////////////////////
// called outside angular, you can create an injector that knows about
// certain modules
///////////////////////////////////////////////////////////////////////////////
$(function() {
// myApp for test directive to work, ng for $compile
var $injector = angular.injector(['ng', 'myApp']);
$injector.invoke(function($rootScope, $compile) {
$('body').prepend($compile('<test>Inside injector</test>')($rootScope));
});
});
Angular将如何知道您刚更改了DOM?您需要在添加html之前编译您的html(使用$ compile服务)。 – Stewie
@Stewie但我没有访问该指令之外的$ compile函数,是否有手动编译的方法?像$('body')。append($ compile(' ')) –
mateusmaso