4

I want to update some values in global array that I keep in a factory. I use the get method to get the data but set function somehow doesn't do its job and the value in the array doesn't get updated. What am I missing?

.factory('messageList', function () {
   var Messages = 
    [
        {   "title":"Cash in", "icon":"ion-social-euro", 
            "dailyValue": "0", "weeklyValue": "0", "monthlyValue": "0", 
            "category": "financial", "active": "true"
        },
        {   "title":"Sales orders", "icon":"ion-social-euro", 
            "dailyValue": "0", "weeklyValue": "0", "monthlyValue": "0", 
            "category": "sales", "active": "true"
        }
    ]

return {
   get: function() {
      return Messages;
   },
   set: function(title, key, newValue) {
       for (var i = 0; i < Messages.length; i++) {
          if(Messages[i].title == title){
            Messages[i].key = newValue;
          }
       }
   }
 }
})

This is how I attempt to update the values in the controller:

messageList.set("Sales orders","dailyValue", $Scope.sum);
3
  • Could you append the code where you're using this code? It doesn't look like it's complete code, but take out of context. Commented Nov 14, 2015 at 7:38
  • 2
    That's not JSON, that's a JavaScript array initializer (aka array literal) containing object initializers (object literals), or really in this case, we'd just say an array with objects in. JSON is a textual notation for data exchange. If you're dealing with JavaScript source code, and not dealing with a string, you're not dealing with JSON. Commented Nov 14, 2015 at 7:41
  • @T.J.Crowder this is a sample data I get from http get call and store it in global array, update it client side and then post it again. I skipped that part because I didn't this it was relevant. but you are right the issue is not related directly to Json. Commented Nov 14, 2015 at 7:44

1 Answer 1

5

As key is a variable, use this

Messages[i][key] = newValue;

Messages[i].key will look for an element in your object with key 'key' rather than a key with the value of your variable

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

4 Comments

Which is great (and correct), but why is an important part of answering a question.
Thank you! Can't believe it was so simple matter :)
I had to learn this at some stage not so long ago too - but you never forget afterwards!
indeed! not after this, I won't forget!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.