Help understanding how to bind the for attribute


#1

Hi I am working on a form component that works with the css library materialize. I got it up and running, but some of the things I had to do to get labels to have the right for value didn’t seem right. I figure since I’m only 2 weeks into ember.js I am just writing hacks when there is a solid way to achieve this. I hope this is the right place for me to inquire.

In a nutshell the component with accept an object array and render a form with different fields based on the object. For materialize to work the label needed to point to the ID of the input.

I first tried just parsing all the ember IDs on the inputs into the respective array and just added a id: property for each object in the aray. Then I tried to bind it to it in the each.

{{#each I in inputs}}
{{input type=I.type}}
<label {{bind attr for=I.id}}>I.input</label>
{{/each}}

This came out with some crazy <label data-bind-attr="435"> (not exact)

My guess here is I.id is populated on didInsertElement, but ember tries to parse this value while it is still undefined. There must be someway to tell ember when its parsing that this attribute belongs to the value of the ID of the {{input}} helper before it.

So I ended up fixing it by just using jQuery to insert the label after each input on didInsertElement: now that it works I am trying to refactor into better ember practices. Can anyone enlighten me on what I was missing to bind the for attribute?


#2

Did you write {{bind attr...}} or {{bind-attr ...}}? (missing dash)


#3

Nicer syntax coming in ember 1.11 yay!


#4

I wish I would have checked my syntax before posting. It was meant to be pseudo code of the issue. I used the right bind because if I changed for=“string literal” it worked but trying to dynamically assign based on the ID of the element above didn’t work. I have some ideas how to fix it. I will report back if I find a solution.


#5

I didn’t find what I originally wanted a way to reference the object but I was able to write an function that turned the inputs name “First Name” ect… into a dasherized version and saved it to the ID then just used the bind attribute to save it.

var tempInputs = this.get('inputs');
for(var x = 0; x < tempInputs.length; x++){
  tempInputs[x].id = tempInputs[x].input.dasherize();
}
this.set('inputs', tempInputs);

Then in the template

{{#if I.isText}}
  <div class="input-field">
    {{input id=I.id type="text"}}
    <label {{bind-attr for=I.id}}>{{I.input}}</label>
  </div>
{{/if}}

Thanks for all who took a look at this to try and help solve it.