2014-12-19 61 views
0

說我有一個聚合物元素<polymer-element> <div id="foo"> {{html}} </div> </polymer-element>,其中html應該是一個HTML格式化字符串,如<p>blah</p>,我要的是,當html變化,聚合物元素也會更改,並使用html作爲其innerHtml,即自動將字符串轉換爲元素並將其插入爲foo的子元素。自動HTML字符串轉換爲元素

聚合物/ polymer_expression可以爲我做這個,或者我必須做一個querySelector(),然後手動設置html爲innerHtml?

回答

2

我的解決辦法是,延伸的股利和使用的DocumentFragment類的自定義元素通過數據綁定將HTML字符串解析到DOM中。

從我Github gist

<!-- Polymer Dart element that allows HTML to be inserted into the DOM via data binding --> 

<link rel="import" href="packages/polymer/polymer.html"> 

<polymer-element name="html-display" extends="div"> 
    <script type="application/dart"> 
    import 'dart:html'; 
    import 'package:polymer/polymer.dart'; 

    @CustomTag('html-display') 
    class HtmlDisplay extends DivElement with Polymer, Observable { 
     @published String htmlContent; 

     // we need this stuff because we're extending <div> instead of PolymerElement 
     factory HtmlDisplay() => new Element.tag('div', 'html-display'); 
     HtmlDisplay.created() : super.created() { 
     polymerCreated(); 
     } 

     @override void attached() { 
     super.attached(); 
     } 

     // respond to any change in the "htmlContent" attribute 
     void htmlContentChanged(oldValue) { 
     if (htmlContent == null) { 
      htmlContent = ""; 
     } 

     // creating a DocumentFragment allows for HTML parsing 
     this.nodes..clear()..add(new DocumentFragment.html("$htmlContent")); 
     } 
    } 
    </script> 
</polymer-element> 

<!-- 
Once you've imported the Polymer element's HTML file, you can use it from another Polymer element like so: 

<link rel="import" href="html_display.html"> 

<div is="html-display" htmlContent="{{htmlString}}"></div> 

*htmlString* can be something like "I <em>love</em> Polymer Dart!" 
-->