2013-02-22 52 views
2

是否可以使用AngularJs而不是頁面呈現模板,但可能在內存中?我需要準備HTML作爲電子郵件發送。 我想我可以渲染隱藏的div的東西,然後以某種方式分配給它的內容變量,但對我來說,它看起來醜陋:(AngularJs中的模板準備

回答

2

你可以看看$編譯功能:http://docs.angularjs.org/api/ng $編譯

例子:

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

}; 
+0

非常感謝!這正是我需要的。也許你也可以提示我如何從控制器中的文件加載模板? – Alber 2013-02-22 12:21:45

+0

@Alber簡而言之,您將使用該服務(請參閱http://docs.angularjs.org/api/ng.$http)。您應該發佈新的SO問題以獲得指導。 – Stewie 2013-02-22 12:41:44

+0

@Alber ...如果你不介意接受答案,如果它回答你的問題。謝謝。 – Stewie 2013-02-22 16:10:36

0

當然,你可以使用$編譯服務呈現模板渲染的模板將是不附加到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> 

我之所以將它們分成兩個不同的功能是因爲,當您編譯並將其鏈接到範圍時,直到下一個摘要之後纔會填充數據。也就是說,如果您在compileTemplate()函數的末尾訪問compiled[0].outerHTML,它將不會被填充(除非您使用超時...)。