2013-06-12 26 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)); 
    }); 
}); 
相關問題