create mail template with $compile in angularjs

馋奶兔 提交于 2019-12-11 13:11:23

问题


I have a large html file with some css in it. This html forms the body for follow up email after filling in a form. The way it is implemented now, is by string concatenation, which I don't like. The new html email body is also larger. I figured I could do it using angulars $compile function but I cant get it to work correctly.

This is the link to the plunk. I have tried this (which is the current state of the plunk) and also the answer of this question.

The completed and 'interpolated' (whatever that means) string is a parameter for a REST call to the server, which will send the actual email. So I would like to keep the creation of the template in a function which the user can execute with for example a ng-click. This is what I mean:

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();
              });

           });
          }

I really wonder why it doesn't work.


回答1:


You need to append complied result to document before get template.html().

Fixed plunker.

With a little trick by using directive to complie template and provide the value back to your controller. Hope it works, any problems let me know 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);
          });
        });
      }
    }


  }


来源:https://stackoverflow.com/questions/37272009/create-mail-template-with-compile-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!