是否可以在沒有dom的情況下獲得編譯後的角度指令html代碼?編譯沒有dom的角度指令模板
這就是我想要的:
var scope = {
list: ["Peter","Paul","Mary"]
},
template = '<ul><li ng-repeat="item in list"{{item}}</li><ul>',
result;
result = desiredFunction(scope, template);
// result should be: "<ul><li>Peter</li><li>Paul</li><li>Mary</li></ul>"
是否有可能得到desiredFunction
?
編輯:
爲了讓我的希望一點點清晰的:我想「編譯」的角度指令模板字符串,而無需指令推入DOM,因爲我不想有它在dom。無論如何,我甚至不需要指令。我只想要的是從模板字符串(template-string + scope-object ==> html-string)編譯的字符串。
是否有任何Angular內部或甚至外部(庫)的方式來做到這一點?
EDIT(2):
以NewDev的回答,糾正我的HTML模板,並添加$timeout
使我下面的解決方案,它的工作原理:
$scope.list = ["Peter", "Paul", "Mary"];
var template = '<ul><li ng-repeat="item in list">{{item}}</li></ul>';
var jqElem = angular.element(template);
$compile(jqElem)($scope);
$timeout(function() {
console.log(jqElem.html());
});
EDIT(3):
關注zerflagL的評論這也是可能的(甚至更短):
$scope.list = ["Peter", "Paul", "Mary"];
var template = '<ul><li ng-repeat="item in list">{{item}}</li></ul>';
var result = $compile(template)($scope)[0];
$timeout(function() {
console.log(result);
});
,你可以返回'element.html()',否?我錯過了什麼? – 2014-10-29 21:08:09
@NewDev看我的編輯。 – heinob 2014-10-30 08:54:50