4

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 }}
1
  • 1
    If you're using lodash/underscore library in your project, you could : {{ timezoneArrOfObj[_.findIndex(timezoneArrOfObj, { value : element.Timezone })].string }} Pretty hard, yes, probably it would be better to decouple this into controller's method. Commented Feb 27, 2016 at 11:05

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.