2013-06-12 24 views
2

我真的很喜欢如何AngularJS可定制标签/元素允许你声明你的应用程序中的指令,但是,当我动态地添加自定义的标签,没有任何反应:为什么angular.js在添加动态元素时不够智能来编译DOM?

angular.module('myApp', []).directive('test', (($compile) -> 
    restrict: 'E' 
    link: (scope, element, attributes) -> 
    $(element).html('<h1>this is a test!</h1>') 
)) 

$('body').append('<test></test>') 

如何建立的一个实例我自定义标签动态?

+1

Angular将如何知道您刚更改了DOM?您需要在添加html之前编译您的html(使用$ compile服务)。 – Stewie

+0

@Stewie但我没有访问该指令之外的$ compile函数,是否有手动编译的方法?像$('body')。append($ compile('')) – mateusmaso

回答

2

你为什么在角度外调用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)); 
    }); 
}); 
相关问题