2015-07-21 92 views
0

Fiddle here在angularJS

添加指令到HTML從另一個指令當我按下一個按鈕,一個模式出現了。在那種模式下,我有一個 <template-placeholder></template-placeholder>

當按鈕被點擊時,我做了if-check,以確保它是正確的按鈕。如果是 - 然後添加另一個指令而不是placeholder

但我無法讓它工作。

這裏是我的指令:

.directive('modalDirective', function(){ 
    return { 
     restrict: 'E', 
     scope: { 
      ctrl: '=', 
      modalId: '@', 
     }, 
     template: ['<div id="{{modalId}}" class="modal fade" role="dialog">', 
         '<div class="modal-dialog">', 
         '<div class="modal-content">', 
         '<div class="modal-header">', 
         '<h4 class="modal-title">Modal Header</h4>', 
         '</div>', 
         '<div class="modal-body">', 
         '<p> {{ ctrl.text }} </p>', 
         '</div>', 
         '<div class="modal-footer">', 
         '<template-placeholder></template-placeholder>', 
         '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>', 
         '</div>', 
         '</div>', 
         '</div>', 
         '</div>'].join(''), 
     link: function(scope, element, attrs) { 
      scope.$watch('modalId', function(val){ 
       if(val == 'protocolModal'){ 
        element.find('template-placeholder').replaceWith('<test-directive></test-directive>'); 
       } 
      }); 
     } 
    } 
}) 

.directive('testDirective', function(){ 
    return { 
     restrict: 'E', 
     template: '<div>this is our other directive speaking.</div>' 
    } 
}); 
+1

你爲什麼不使用ng-if。這將簡化事情。 –

+0

是一個指令還是一個虛擬元素? –

+0

你正在替換內容而不編譯它 – nada

回答

1

您需要使用$compile

.directive('modalDirective', ['$compile', function($compile){ 
    ... 
    link: function(scope, element, attrs) { 
     scope.$watch('modalId', function(val){ 
      if(val == 'protocolModal'){ 
       element.find('template-placeholder').replaceWith($compile('<test-directive></test-directive>')(scope)); 
      } 
     }); 
    } 
}]) 

更新小提琴:https://jsfiddle.net/L0jns64m/3/

1

爲什麼在modalId看?你可以只用一個NG-IF:

'<div class="modal-footer">', 
'<test-directive data-ng-if="modalId == \'protocolModal\'"></test-directive>', 
'<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>', 
'</div>', 

這裏正在與它小提琴:http://jsfiddle.net/aL0er9rv/

0

更換模板的佔位符

<ng-if="protocolModal" test-directive></test-directive> 

NG,如果將兩個彙編的護理併爲你而毀滅。這很好。