2014-09-25 62 views
0

我有一種情況,當用戶點擊一個鏈接,我想自定義元素插入到DOM例如插入指令動態和編譯

//user clicks  
    $scope.click = function() { 
      var el = $compile("<my-directive></my-directive>")($scope); 
      $element.after(el); 
    }; 

的我的指令....指令具有HTML模板..比方說(template1.html)

<p>My Template for my-directive</p> 
{{SomeProperty}} 

我的指導性的定義如下

module.directive('myDirective', ['$compile', function ($compile) { 
    return { 
     restrict: 'E', 
     replace: true, 
     templateUrl: '/template1.html', 
     scope: true 
    }; 
}]); 

如果我們假設myDirective中的範圍在運行此代碼後實際上具有SomeProperty的值,那麼確實將my-directive插入到DOM中並由模板替換 - template1.html,但{{SomeProperty}}尚未替換爲所有!我該怎麼做呢??

更多細節

回答

0

你在你的Plunkr做$compile("<my-directive></my-directive>")($scope.$parent);。刪除.$parent

Chenge模板:

<p>My Template for my-directive</p> 
{{d.SomeProperty}} 

像你一樣d in data

它的作品:)

0

我不知道你是否有任何其他錯誤見Plunkr,但我發現,消除replace:true使得它爲我工作。

我不確定到底發生了什麼,但不知何故,您將指令添加到dom +立即替換它的交互導致它不起作用。

我注意到的另一件事是,通過使用$element.after(el);您最後得到的是一個超出控制器範圍的元素。它不在控制器的範圍內。不幸的是,我只在我的朋友看到​​這個,所以不知道這是否也會影響到你。

Plunkr here

+0

嗯,你可以看看我的plunkr? http://plnkr.co/edit/5Qnv6i8jhyRwMEWtRQO7?p=preview – Paul 2014-09-25 05:01:31