我真的很喜欢 AngularJS 通过允许您在应用程序中声明指令来启用自定义标签/元素,但是,当我动态附加自定义标签时,什么也没有发生:
angular.module('myApp', []).directive('test', (($compile) ->
restrict: 'E'
link: (scope, element, attributes) ->
$(element).html('<h1>this is a test!</h1>')
))
$('body').append('<test></test>')
如何动态构建自定义标签的实例?
为什么你在 Angular 之外调用 jquery ?通常,您会在 Angular 指令内部执行某些操作,并且可以访问 $compile。如果您绝对需要外部访问,您可以创建一个注入器。(笨蛋) http://plnkr.co/edit/hMMstX9pkdcPREESwrzI?p=preview
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));
});
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)