If I have a JSOn which has an array element like
model.person = {“name” : “a”,
“schools” : [
{“id” : 1,
“city” : “SF” },
{ “id” : 2,
“city” : "NYC}
]
}
And my templates has
{{#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
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}}
1 Like
So basically Ill have to do a mapBy for all the properties I have in an array. So, if I have 10 properties I
ll 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.
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);