pandaseal pandaseal - 6 months ago 14
Javascript Question

Get index of current object in array? Pass current object to a function. Angular JS

I am trying to call a function from an object in an array. (The objects of the array are placed on a map.) The function should evaluate what 'status' the object has, and return a url for an icon based on the status. I have to pass the current object to the function.. But how do I do it?

My array of objects:

mvc.models = [{
id: "1",
icon: evaluateColor(currentObject),
status: 'green'
},
{
id: "2",
icon: evaluateColor(currentObject),
status: 'red'
}];


My function:

function evaluateColor(currentObject) {
if (currentObject.status === 'green') {
return 'images/green_marker.png'
}
else if (currentObject.status === 'yellow') {
return 'images/yellow_marker.png'
}
else {
return 'images/red_marker.png'
}
}


I have tried to pass the object to the function by passing 'this', but the object logs as undefined. Probably because 'this' refers to the controller and not the object.

mvc.models = [{
id: "1",
icon: evaluateColor(this),
status: 'green'
},
{
id: "2",
icon: evaluateColor(this),
status: 'red'
}];


And if someone wants to see the html: (the objects are houses that should be shown on an angular google maps)

<ui-gmap-markers
models='mvc.models'
coords="'coords'"
icon="'icon'"
>
</ui-gmap-markers>


Can someone point me in the right direction? Thanks!

Answer

You don't need to pass whole object to evaluateColor. Modify it to

function evaluateColor(status) {
  if (status === 'green') {
    return 'images/green_marker.png'
  }
  else if (status === 'yellow') {
    return 'images/yellow_marker.png'
  }
  else {
    return 'images/red_marker.png'
  }
}

and call it with evaluateColor('green'/'yellow') , as you anyways have the color available while initializing the object. this.status will not work as the object declaration is still not complete.

Alternatively, you can call initialize models without icon attribute and call this function:

for(var i in models){
   models[i].icon = evaluateColor(models[i].status);
}

Hope this solves your query.. :)

Comments