6

I want to pass data that I have on a variable to a Polymer component via attribute.

This is the code:

<script>
  var item1 = {
      title: "Title 1",
      status: "accepted"
  };
</script>

<bm-card item="{{item1}}" otherAttribute="hello">

The otherAttribute gets the data on the custom element but item does not arrive.

How could item attribute be populated from the item1 variable ?

jordiburgos
  • 5,964
  • 4
  • 46
  • 80

1 Answers1

4

To use data-binding outside of <polymer-element> you need <template is="auto-binding">: https://www.polymer-project.org/docs/polymer/databinding-advanced.html#bindingoutside

However, you can just set the property directly in js:

<bm-card otherAttribute="hello">

document.addEventListener('polymer-ready', function() {
  document.querySelector('bm-card').item = item1;
});

The reason you have to wait for polymer-ready is to ensure the element has upgraded in the DOM and has it's properties/methods defined.

ebidel
  • 23,921
  • 3
  • 63
  • 76
  • After reading the documentation and testing, the only way to pass data to a polymer element is using JavaScript. auto-binding still needs some JS to send the data. – jordiburgos Nov 16 '14 at 23:17
  • Yes, something needs to tie the js world to the HTML world. – ebidel Nov 17 '14 at 05:31
  • It is done "automagically" in AngularJS, I would prefer something like that. – jordiburgos Nov 17 '14 at 10:48
  • 1
    That's not true. In Angular, you set data models on the scope (or use expressions in bindings) and the template picks them up. Same is the case here. In Polymer, you can also pass an array/object directly as an attribute. If you hint the type, it's (de)serialized for you. https://www.polymer-project.org/docs/polymer/polymer.html#attrhinting – ebidel Nov 17 '14 at 16:36
  • Since Polymer 1.0, you can use window.addEventListener('WebComponentsReady', function(){ document.querySelector('bm-card').item = item1; }); https://www.polymer-project.org/1.0/docs/migration#polymer-ready – ling Aug 24 '16 at 11:11