create mail template with $compile in angularjs

2019-07-31 19:51发布

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条回答
女痞
2楼-- · 2019-07-31 20:09

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


  }
查看更多
登录 后发表回答