Home > Article > Web Front-end > Instructions for using dom-if and is attributes in JS framework Polymer_Basic knowledge
We often have the need for template rendering based on the value of a certain attribute, which is the most basic branch statement. There is ng-if available in Angular, and of course there is dom-if in Polymer. In fact, dom-if is a very simple thing. It is just the access point for this topic. What I want to introduce is actually the is attribute.
Like the dom-repeat introduced before, dom-if is used on the template element through the is attribute. For example, in the following example, two templates decide who should be rendered based on a Boolean value on a bound control
Run
<script> var Polymer = { dom: 'shadow' }; </script> <base href="http://www.web-tinker.com/share/" /> <link rel="import" href="polymer/polymer.html" /> <dom-module id="demo-test"> <template> <input type="checkbox" checked="{{checked::change}}"> <template is="dom-if" if="[[checked]]">true</template> <template is="dom-if" if="[[!checked]]">false</template> </template> <script> Polymer({ properties: { checked: { value: false } }, is: 'demo-test' }); </script> </dom-module> <demo-test></demo-test>
Whether it is dom-if or the previous dom-repeat, what exactly do these is attributes specify? In fact, it is the same as Angular. They are both Directive concepts, but Polymer does not call it Directive. We can completely create such a thing ourselves. For example, in the following example, we add an is="demo-test" thing to the div element
Run
<script> var Polymer = { dom: 'shadow' }; </script> <base href="http://www.web-tinker.com/share/" /> <link rel="import" href="polymer/polymer.html" /> <script> Polymer({ is: 'demo-test', extends: 'div', <!-- 关键就在这里 ready: function(e) { this.innerHTML = '我是一个 demo-test'; } }); </script> <div is="demo-test"></div>
When defining, specify a tag name through extends to get an is directive. The above example is the simplest usage. We can create Shadow DOM ourselves and do what we want. In fact, Polymer's built-in dom-repeat, dom-if and other dom-* are also defined in this way. But this thing looks very complicated in detail, and my article is just an entry-level thing. If you want to know more specific usage, you should read the source code (I can't even find the official document where it is defined).