2016-09-26 42 views
1

有很多關於如何使用AngularJS路由動態加載HTML和腳本的例子。我的情況不同,我無法找到如何去做。如何在AngularJS中按需加載HTML片段?

假設這個代碼已經加載到瀏覽器:

<div ng-controller='masterController'> 
    <button ng-click='loadOtherHtmlOnDemandAndAppendItAfterMe'></button> 
</div> 
<script> 
    app.controller('masterController', ['$scope', function($scope){ 
     $scope.loadOtherHtmlOnDemandAndAppendItAfterMe = function() { 
      /* 
       how can I load another HTML file, 
       that contains it's related script too here, on-demand 
      */ 
     }; 
    }]); 
</script> 

現在我明白了很多人現在可能嚷嚷你就錯了,這不是AngularJS應該如何工作,和東西,但我們被困在微服務和混搭Web UI的體系結構中,其中一個加載到瀏覽器的模塊觸發了一個事件,說它需要一個功能,另一個模塊正在監聽該事件,應該加載根據需要提供相關功能。 URL不會更改,並且此處不使用路由。

回答

2

只使用一個templateCachecompile服務,這種方式:

app.controller('masterController', ['$scope', '$compile', '$templateCache', function($scope, $compile, $templateCache){ 
    $scope.loadOtherHtmlOnDemandAndAppendItAfterMe = function() { 
     var template = $compile($templateCache.get('yourHTMLFile.html'))($scope); 

     angular.element('div').append(template); //append your compiled element wherever you want 
    } 
}]); 

簡而言之:templateCache是​​容易抓住的HTML文件/腳本,並在一個變量裹在裏面,$編譯讓所有的動態服務行爲的作品(角度綁定,JavaScript等)

+0

如果有一個控制器在HTML模板旁邊註冊了該控件,該怎麼辦?因爲我得到'xController不是函數,所以在加載這個模板時得到了undefined':'

{{ name }}
' –