AngularJs中的模板准备

时间:2013-02-22 11:48:34

标签: angularjs

是否可以使用AngularJs渲染模板而不是在页面上,但可能在内存中?我需要准备html作为电子邮件发送。 我想我可以在隐藏的div中渲染一些东西,然后以某种方式将内容分配给变量,但对我来说它看起来很难看:(

2 个答案:

答案 0 :(得分:2)

您可以查看$ compile函数:http://docs.angularjs.org/api/ng。$ compile

示例:

function MyCtrl($scope, $compile){
  // You would probably fetch this email template by some service
  var template = '</div>Hi {{name}}!</div></div>Here\'s your newsletter ...</div>'; // Email template

  $scope.name = 'Alber';

  // this produces string '</div>Hi Alber!</div></div>Here\'s your newsletter ...</div>'
  var compiledTemplate = $compile(template)($scope); 

};

答案 1 :(得分:0)

当然,您可以使用$ compile服务来呈现模板。呈现的模板将是未附加到DOM树的DOM节点。而且您不必附加它来获取其内容。你可以这样做:

<!doctype html>
<html ng-app="myApp">
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
    <script type="text/javascript">
    var myApp = angular.module('myApp', []);

    myApp.controller('MainCtrl', ['$scope', '$compile', function($scope, $compile){
        var compiled;
        $scope.compileTemplate = function() {
            var template = '<ul><li ng-repeat="i in [1, 2, 3]">{{i}}</li></ul>';
            var linker = $compile(template);
            compiled = linker($scope);
        }
        $scope.sendEmail = function() {
            alert("Send: " + compiled[0].outerHTML);
        }
    }]);
    </script>
</head>
<body ng-controller="MainCtrl">
    <button ng-click="compileTemplate()">Compile template</button>
    <button ng-click="sendEmail()">Send email</button>
</body>
</html>

我将它们分成两个不同的函数的原因是因为当你编译并将它链接到作用域时,模板在下一个摘要之后才会填充数据。也就是说,如果您在compiled[0].outerHTML函数末尾访问compileTemplate(),它将不会被填充(除非您使用超时...)。