How do I access an array that is inside a model - in a controller


#1

If I have a JSOn which has an array element like :slight_smile:

model.person = {“name” : “a”, “schools” : [ {“id” : 1, “city” : “SF” }, { “id” : 2, “city” : "NYC} ] }

And my templates has :slight_smile: {{#each model.person.schools as |person_school|}}

The question is If I want to access this person_school.city value of the model in the controller for this array traversal how would I do that since,

this.get(‘person_school’) won`t work


#2

Little confused about the question. Are you wanting an array of all the model.person.schools.@each.city's within the controller .js file? Or trying to access it within the {{#each}} helper in the controller template?

In the controller .js file, use a mapBy() computed property:

schoolCities : Ember.computed.mapBy('model.person.schools', 'city')

In the controller template within the {{#each}} helper:

{{#each model.person.schools as |person_school|}}
    {{person_school.city}}
{{/each}}

#3

So basically Ill have to do a mapBy for all the properties I have in an array. So, if I have 10 properties Ill have to have 10 computed properties like schoolCities : Ember.computed.mapBy(‘model.person.schools’, ‘city’)

Clarification :- I want to access whatever array element the each helper in the template is traversing through, into the controller. So, eg : if {{#each model.person.schools as |person_school|}} {{person_school.city}} {{/each}}

Is going through id: 1, city: SF I want to access that in the controller Is going through id: 2, city: NYC I want to access that in the controller using this.get or something else.

I basically want to access the current element being traversed in the array inside the model inside the controller.


#5

Not possible, you’ll need to create your own Helper to put that sub-logic. So then you call that Helper within the {{#each}} block.

{{#each model.person.schools as |person_school|}}
  {{my-helper-name person_school}}
{{/each}}
// app/helpers/my-helper-name.js
export function myHelperName([school]) {
  return school.get('city').toUpperCase(); // Or whatever you need to do
}
export default Ember.Helper.helper(myHelperName);