我是比較新的創建自定義角指令,和我想要在我的應用程序,它是一系列的JQuery組分組成,其中獲得嵌套在彼此替換頁面。如何動態插入和刪除一個嵌套的Angular自定義指令?
我想要創建一組自定義Angular指令,我可以在彼此中嵌套,允許用戶構建一種表單,同時允許它們刪除並重新添加嵌套在另一個指令中的任何指令如果他們需要的話。
我不知道如何根據用戶的選擇動態地將一個指令插入另一個指令,以及如何在指令中設置此指令,以便可以刪除,重新添加並重新編譯給定指令的子代。
到目前爲止,我已經提出的唯一(不復雜的)方法是將雙向綁定到指令的隔離範圍上的屬性,並確定指令的內容如此,但是在更改此屬性時父範圍對象,該指令的DOM不重新編譯,所以我相信有一個更好的方法來做到這一點。
我假設我可能需要使用transclusion或以某種方式鏈接功能,所以有這方面的指導,非常感謝!
當前的嘗試:
app.directive("testCustomMapperThings", function($compile) {
var testTemplate1 = '<div>THIS IS FIRST THE DYNAMICALLY COMPILED TEST TEMPLATE 1</div>';
var testTemplate2 = '<div>THIS IS SECOND THE DYNAMICALLY COMPILED TEST TEMPLATE 2</div>';
var getTemplate = function(contentType) {
var template = '';
switch(contentType) {
case 'testTemplate1':
template = testTemplate1;
break;
case 'testTemplate2':
template = testTemplate2;
break;
}
return template;
};
var linker = function(scope, element, attrs) {
//reads the scope's content attribute (2 way bound to this directive's isolate scope) and sets as DOM
element.html(getTemplate(scope.content.testContent)).show();
//compiles the 2 way bound DOM, recompiles directive on changes to attributes. todo: CHECK DIRECTIVE RECOMPILES ON CHANGES TO ATTRIBUTES
$compile(element.contents())(scope);
};
return {
restrict: "E", //can only be an element
link: linker, //link function
scope: { //isolate scope, 2 way bind to a 'content' attribute
content:'='
}
};
});
使用此指令的DOM,我試圖改變$ scope.content對象但該指令的內部內容並沒有重新編譯:
<test-custom-mapper-things content="testContent"></test-custom-mapper-things>
<button ng-click="changeContent()">Click to change the test content and see if DOM recompiles</button>
控制器指令的父範圍:
$scope.testContent = {
testContent : "testTemplate1"
};
$scope.changeContent = function() {
if($scope.testContent.testContent == 'testTemplate1') {
$scope.testContent.testContent = 'testTemplate2';
} else {
$scope.testContent.testContent = 'testTemplate1';
}
};
這行之有效的感謝,因爲獲得了$編譯服務更深入的瞭解和管理它。再次感謝。 –