簡體   English   中英

如何阻止angularJS解析/運行指令或代碼塊?

[英]How to block angularJS from parsing/running a directive or code block?

我的問題聽起來很簡單,但我還沒有找到解決方案,而且我在谷歌和SO搜索了很多。

我想為我的自定義指令創建一個演示html頁面,在其中我想在代碼塊中顯示指令的標記(類似於它在angular docs中的方式 )。 但我不需要它是動態的(沒有語法高亮,沒有標簽)。

對我來說,將代碼與純文本一樣可以,但Angular會解析該指令並執行代碼。

如何阻止角度來執行指令?

它應該如下所示:

Text that describes the directive ..............

    <directive1 parameter1="test"></directive1>

Then the rendered directive result here

到目前為止我嘗試過什么?

  • 移動描述下面的ng-app:不起作用(指令標記將被隱藏)
  • 嵌套在不同的html標簽span, pre, code但是沒有工作。
  • 將angular指令放在iframe 不工作,在jsFiddle中總是空的。

在這里,我設置了一個簡單的jsFiddle演示。 (我的指令有點復雜,但它顯示了問題。)

 angular.module('myApp', []) .directive('simpleDirective', function() { return { restrict: 'EA', template: 'I\\'ma simple directive!' }; }); 
 pre { background: lightgray; } 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp"> <h2>Usage of directive</h2> <p>Here I'd like to describe my directive and show the directive in a code block (but how do I block angular to execute the directive?!)</p> <pre><code> <simple-directive></simple-directive> </code> </pre> ^--- the above directive must not run. <!--<div ng-app="myApp"> doesn't work--> <p>The following directive code shows the result:</p> <simple-directive></simple-directive> <!-- </div> --> </div> 

一個簡單的解決方案是使用html for directive設置元素text

angular.module('myApp', [])
.directive('code', function(){
    return{
        restrict:'E',
        link:function(scope, elem){
            elem.text('<simple-directive></simple-directive>')
        }
    }
});

當然,您可以簡化此操作以從數據模型中提供html,從而擁有許多像這樣的塊,其范圍由屬性定義,或者從腳本標記中的一個模板中提取

當您在angular之外插入html並且不使用$compile時,Angular將無法$compile

另一個簡單的解決方案是將其放在腳本標記中並在該標記上設置display:block

HTML

<script id="script-block" type="text/demo">
    <simple-directive></simple-directive>
</script>

CSS

#script-block{    
    display:block;
    background: yellow
}

腳本標記方法也可以作為指令

就個人而言,我會使用語法熒光筆為你做這一切。 周圍的人有很多選擇

DEMO

你總是可以對<>進行html編碼:

所以<code>塊看起來像:

<code>&lt;simple-directive&gt;&lt;/simple-directive&gt;</code>

你可以通過做這樣的事情在JavaScript中做到這一點

已編輯的片段:

 angular.module('myApp', []) .directive('simpleDirective', function() { return { restrict: 'EA', template: 'I\\'ma simple directive!' }; }); 
 pre { background: lightgray; } 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp"> <h2>Usage of directive</h2> <p>Here I'd like to describe my directive and show the directive in a code block (but how do I block angular to execute the directive?!)</p> <pre><code> &lt;simple-directive&gt;&lt;/simple-directive&gt; </code> </pre> ^--- the above directive must not run. <!--<div ng-app="myApp"> doesn't work--> <p>The following directive code shows the result:</p> <simple-directive></simple-directive> <!-- </div> --> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM