2014-09-18 41 views

回答

1

您可以使用內聯模板中使用腳本標記(https://docs.angularjs.org/api/ng/directive/script

<script type="text/ng-template" id="myDivTemplate"> 
     Hello my name is {{name}} 
    </script> 

然後它作爲插值

聲明10
$scope.report = $interpolate($("#myDivTemplate").html())($scope); 
+0

由於您已經定義了模板,從模板緩存中抓取它不會更好嗎? '$ interpolate($ templateCache.get('myDivTemplate'))($ scope);' – adam0101 2014-09-18 16:31:18

+0

是的。這樣,你就不會對任何不在指令內的DOM操作感到內疚。另外,更好的辦法是在'cache:$ templateCache'中使用'$ http',因爲這樣你就不必假設模板_will總是在頁面中。 – gustavohenke 2014-09-18 16:39:10

+0

使用'$ templateCache.get('myDivTemplate')'將會更清潔 – 2014-09-18 16:41:03

3

使用ngNonBindable指令。從文檔摘自:

<div>Normal: {{1 + 2}}</div> // => Normal: 3 
<div ng-non-bindable>Ignored: {{1 + 2}}</div> // => Ignored: {{1+2}} 

然而,當心,這可能不會編譯出現在該元素的其他指令。


另一種選擇(這在我看來是最正確的)是創建一個指令,並捕獲元素在編譯階段的內容,然後只插值它時,你需要:

app.directive("myDirective", function($interpolate) { 
    return { 
    compile: function(tElement) { 
     var raw = tElement.html(); 
     return function(scope, element) { 
     var interpolated = $interpolate(raw)(scope); 
     // do something with it 
     }; 
    } 
    }; 
}); 
+0

謝謝。 ngNonBindable的作品,但我認爲使用模板對我來說可能是正確的。 – adam0101 2014-09-18 16:32:43