【问题标题】:How to prevent Jade Template parsing HTML attribute如何防止 Jade Template 解析 HTML 属性
【发布时间】:2013-09-24 11:55:56
【问题描述】:

我将 Jade Template 与 Angular JS 结合使用,并在 Angular 的控制器中定义了这样的转发器处理简单数组:$scope.ids = ['demo1', 'demo2']

.controls(ng-repeat="controlId in ids")
  <div id="{{$index}}">{{$index}}</div>

无论我做什么 Jade 都会尝试解析传递给 SELECT 标记的所有内容,因此它总是从标记的属性中删除 $index 变量。作为 HTML 的结果,我总是看到以下内容:

<div id="">0</div> // ID attribute is always empty because Jade replaces it
<div id="">1</div> // at the same time HTML of the tag was rendered correctly

问题:如何防止 Jade 解析这个 HTML 属性并在结果 HTML 中打印字符串?

P。 S. 我尝试了以下语法,但它不起作用...建议?

id="|{{$index}}" // id is empty
id!="{{$index}}" // id is empty
id="!{{$index}}" // syntax error
id="!{{controlId}}" // syntax error
{:id => {{$index}}} // does not add ID at all

P。 P.S. 只是为了解释为什么我把 Jade 和 HTML 搞混了——我尝试使用“jade only”语法,但它也不起作用:

.controls(ng-repeat="controlId in ids")
  .demo(id="{{$index}}") {{$index}}

【问题讨论】:

  • 它没有理由不工作。你为什么使用 .controls 是玉。和
    哪个是 html?可能您的 div 超出了 html 中 .controls 的范围。
  • @Sangram Singh:我尝试只使用 Jade 语法,直到我意识到我只需要原始 HTML 这就是为什么我在这里简单地展示两种不同的语法 - “仅限 Jade 语法”不起作用太
  • 问题不在于 Jade。我正在使用 id={{$index}} 并且它有效。什么是ids = ?
  • @Sangram Singh : 回复上面 $scope.ids = ['demo1', 'demo2']

标签: javascript angularjs pug


【解决方案1】:

尽量避免这样的解析:

!{{$index}} <-- Escaped

参考这篇文章:How to make Jade stop HTML encoding element attributes, and produce a literal string value?

关于这个问题:https://github.com/visionmedia/jade/issues/198

并说它是否有效!

【讨论】:

  • 是的,我看到了这些问题,不幸的是它不起作用,我更新了我的答案来描述当我使用 !{{$index}} 或 !{{controlId}} 时会发生什么
【解决方案2】:

最近我发现这个讨论是由 Sangram 发起的:

{{$index}} of ng-repeat computed after linker function of angular directive. $compile it?

我意识到 Sangram 在这点上是对的——这不是 Jade 的问题——这就是 Angular 渲染模板的方式。

有一个解决方案 - 在 $evalAsync 中调用链接函数 - 可能这是一个不错的选择,但在我的情况下,我需要立即设置控件的 ID,所以我想出了这个解决方案 - 如果我无法设置 ID -我可以生成它:

app.directive('tags', ['$rootScope', function($rootScope) {

    var controlIndex = 0;

    var linker = function(scope, element, attrs) {

    // *** Control ID *** //

        element[0].id = attrs.id || 'control' + (++controlIndex);

        ...
    }

    return {
        restrict: 'EA',
        templateUrl: 'tags/template.html',
        link: linker
    }
}]);

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签