don
don

Reputation: 4522

Referencing to the value of an object inside angular {{ }} html markup

I'm in AngularJS 1 and I would like to show the value of the element I'm displaying, by referencing to the value of an object that has for key the value of the element.

Currently my implementation is very inefficient, as I have two versions of the same values, on as an Array of Objects, the other as an Object (which I use to create the select element).

Example:

timezonesArrOfObj = {
    { value : "Europe/Dublin", string : "(GMT) Dublin"},
    { value : "Europe/Lisbon", string : "(GMT) Lisbon"},
    { value : "Europe/London", string : "(GMT) London"}
}

timezonesObj = {
    "Europe/Dublin" : "(GMT) Dublin",
    "Europe/Lisbon" : "(GMT) Lisbon",
    "Europe/London" : "(GMT) London"
}

Currently, when I want to display the value, I do this:

{{ timezonesObj[element.Timezone] }}

However, it would be more efficient to reuse the timezonesArrOfObj, but how could I associate the proper key with the value of element.Timezone to show the right timezonesArrOfObj[ (index of key == element.Timezone) ].string?

Btw, I need the timezonesArrOfObj as I want to be sure of the order in which timezones are listed in the select element.

// EDIT

Merging the comment from xSaber and the response from Vaibhav, I've ended up doing this:

.filter('getObjString', function() {
    return function(args){
        return args.obj[_.findIndex(args.obj, { value : args.val })].string 
    };
});

and html:

{{ { val : element.timezone, obj : timezonesArrOfObj } | getObjString }}

Upvotes: 4

Views: 544

Answers (1)

Vaibhav Pachauri
Vaibhav Pachauri

Reputation: 2671

It would be great if you can use a filter instead.

Something like below :

app.filter('myFilter', function() {
  var timezonesArrOfObj = [
        { value : "Europe/Dublin", string : "(GMT) Dublin"},
        { value : "Europe/Lisbon", string : "(GMT) Lisbon"},
        { value : "Europe/London", string : "(GMT) London"}
    ];
  return function(input, arg){
    angular.forEach(timezonesArrOfObj, function(key, value){
      if(arg == key.value){
        console.log('yes they are equal');
        return key;
      }
    });
  };
});

in HTML :

all you need is to use this filter wherever you are binding your result :

{{element.timezone | myFilter}}

I hope this helps. Do let me know in case of any issue.

Upvotes: 1

Related Questions