2014-10-29 110 views
1

是否可以在沒有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); 
    }); 
+0

,你可以返回'element.html()',否?我錯過了什麼? – 2014-10-29 21:08:09

+0

@NewDev看我的編輯。 – heinob 2014-10-30 08:54:50

回答

4

您可以編譯而不使用DOM中的元素。

假設你有適當的注射,你可以這樣做:

var template = '<ul><li ng-repeat="item in list"{{item}}</li><ul>'; 
var jqElem = angular.element("<div>").html(template); 
$compile(jqElem)($scope); 

在這一點上,然而,innerHTML仍然沒有編制。爲此,我們需要等到$ digest週期結束。我知道如何做到這一點的方法之一是使用$超時,但是這意味着你的函數必須返回一個承諾

return $timeout(function(){ return jqElem.html(); }, 0); 

附:

你可以通過模板直接進入$compile功能,但請注意,.html()將返回內部HTML,所以你可能需要做類似下面來獲得完整的模板:

return $timeout(function(){ return jqElem[0].outerHTML; }, 0); 
在鏈接功能
+1

您可以直接將'template'傳遞給'$ compile'。 – zeroflagL 2014-10-30 09:49:02

+0

@NewDev你試過了嗎?看到我第二個編輯... – heinob 2014-10-30 10:02:59

+0

@zeroflagL如果我直接傳遞模板,我應該從哪裏獲得編譯後的字符串? $編譯返回不同的東西... – heinob 2014-10-30 10:04:01