cdjackson
cdjackson

Reputation: 137

EmberJS calling controller function within #each

I'm trying to call a controller function inside a #each template to check if the model is selected. This needs to receive the model for each loop iteration.

jsbin is here http://emberjs.jsbin.com/bemos/4/edit

I've tried using the following template, but adding a parameter to {{controller.selected}} results in ember throwing an exception, or not doing anything (the result seems to be different in jsbin).

{{#each model}}
    <li><a hres="#" {{action "clickItem" this}}>{{label}} -- selected is {{controller.selected name}} </a></li>
{{/each}}

My function in the controller looks as follows

selected: function(id) {
    var list = this.get("selectedList");
    console.log("Checking sel for", id);
    if(list.contains(id))
        return true;
    return false;
}.property("selectedList")

In the jsbin, I expect to be able to click on the "Hello 1"/"Hello 2" elements, and this should change the part of the text that says "selected is false" to true. It should also update the number of items selected in the bottom. Currently, this shows 1 item is selected (since the default is selectedList:["2"]) however "Hello 2" says "selected is false" - this should say "true".

(I should add I'm pretty new to EmberJS as have been working with ExtJS for a few years!). Thanks

Upvotes: 1

Views: 869

Answers (1)

lame_coder
lame_coder

Reputation: 3105

Do you really have a problem in code ? I guess no, since your bin is working fine and even clickItem is working as well. In your local environment where you are facing this issue, I think you are not using same version of handlebars and ember. Please check if you are using below,

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
  <script src="http://builds.handlebarsjs.com.s3.amazonaws.com/handlebars-v1.3.0.js"></script>
  <script src="http://builds.emberjs.com/tags/v1.6.1/ember.js"></script>

Update 1 -

Here is the bin I tried to update - http://emberjs.jsbin.com/veqoqocu/1/edit Its not fully functioning but fixes some issue.

There are multiple problems,

  1. You should use ArrayController for lists, redesign your example otherwise selected property will never work the way you want. Here is a good example - http://emberjs.com/guides/controllers/representing-multiple-models-with-arraycontroller/
  2. push & pop needs to be pushObject and popObject
  3. computer property on array works like - }.property('selectedList.[]')

Upvotes: 1

Related Questions