2016-05-17 54 views
1

我有一個大的HTML文件,其中包含一些CSS。填寫表格後,該html形成了用於跟進電子郵件的正文。現在它的實現方式是通過字符串連接,我不喜歡。新的HTML電子郵件正文也更大。我想我可以使用angulars $編譯功能,但我不能讓它正常工作。

這是link to the plunk。我試過this(這是當前的狀態),也是the answer of this question

完成和'插入'(不管這意味着什麼)字符串是REST調用服務器的參數,它將發送實際的電子郵件。所以我想在一個函數中保留模板的創建,用戶可以使用例如ng-click來執行該模板。這就是我的意思:

composer.$inject = ["$http", "$compile", "$scope", "$templateRequest", "$timeout"]; 
     function composer($http, $compile, $scope, $templateRequest, $timeout) { 

      $scope.person = { 
      firstname:"jonny", 
      lastname:"Bravo" 
      }; 

      compose(); 


      function compose() { 
      $templateRequest("template.html").then(function(html){ 
       var template = angular.element(html); 
       console.log(template); 
       $compile(template)($scope); 
       console.log(template); 

       $timeout(function() { 
       $scope.htmlitem = template.html(); 
       }); 

      }); 
      } 

我真的很奇怪它爲什麼不起作用。

回答

2

您需要在獲得template.html()之前追加complied resultdocument

固定plunker

通過使用directive編寫模板並將值提供給您的控制器有一個小技巧。希望它的作品,任何問題讓我知道PLZ。

.directive("htmlBuilder", htmlBuilder); 

htmlBuilder.$inject = ["$http", "$compile", "$templateRequest", "$timeout"]; 

    function htmlBuilder($http, $compile, $templateRequest, $timeout) { 

    return { 
     restrict: 'EA', 
     require: 'ngController', 
     link: function(scope, $elements, attrs, ctrl) { 

     $templateRequest("template.html").then(function(html) { 
      var template = angular.element(html); 
      $compile(template)(scope); 

      //Apend to document before get innerHTML 
      $elements.append(template); 

      $timeout(function() { 
      var res = $elements.html(); 
      ctrl.setResult(res); 
      }); 
     }); 
     } 
    } 


    } 
+0

非常感謝!我仍然有另一個問題:模型上的更改不反映在編譯的html中。我最好在我原來的問題中解釋一下。爲了更好地反映這一點,我更新了重拳。然而,你的回答確實回答了我的問題(我真的不知道我應該追加模板),所以它的唯一公平就是給你信任。謝謝! –

+0

檢查[固定搜索演示](https://plnkr.co/edit/ZfRKlyftC3mPuMSrtxVO?p=preview)。 –

+0

@ ocket-san,歡迎您,並修正觀看和反映在編譯的HTML。當使用**指令的**隔離範圍**時,可以通過'scope。$ parent'訪問控制器的'$ scope'。 –