Search code examples
javascriptmodel-view-controllerember.jsember-data

Toggling and binding a boolean value with a checkbox in Ember.js


I’m trying to toggle between a true and false value with a bound checkbox (photoApproved), but having no so luck in my controller code.

Here’s the photos_controller.js:

App.PhotosController = Ember.ArrayController.extend(

  photoApproved: ((key, value) ->
    model = @get("model")
    if value is 'undefined'
      model.get "approved"
    else
      model.set "approved", value
      model.save()
      value
  ).property("model.approved")

)

Here’s the template file photos.hbs:

<h1>Photos</h1>

<ul>
  {{#each controller}}
    <li class="masonry-brick">
      <h3>Approved: {{approved}}</h3>
      {{input type="checkbox" checked=photoApproved class="toggle"}}
      {{#link-to "photo" this}}{{name}}{{/link-to}}
      <img {{bind-attr src=image_url}} alt="Logo">
    </li>
  {{else}}
    <li>There are no photos.</li>
  {{/each}}
</ul>

{{outlet}}

And finally, here’s the model:

App.Photo = DS.Model.extend(
  name: DS.attr("string")
  description: DS.attr("string")
  image_url: DS.attr("string")
  approved: DS.attr("boolean")
)

How should I change my photoApproved function to get things working properly?


Solution

  • Ember 2.4 answer:

    <input type="checkbox"
      checked="{{if info.show_in_email 'checked'}}"
      onclick={{action (mut info.show_in_email)
      value="target.checked"}} />
    

    where info is a ember model and show_in_email is a boolean field.