Search code examples
angularjsangularjs-scopeangularjs-service

What is the best way to store key value pairs in Angular JS


I have an angular app that consists of a main page and partial pages. Partial pages are displayed in ui-view

<div class="" ui-view>

</div>

To store a global variable I use $scope.$parent.variable_name. So I declared the variable in the base controller:

$scope.$parent.my_array = [];

and attempted to fill it from the partial page controller using:

 $scope.$parent.my_array.push({ 'KeyId': KeyVariableID, 'KeyValue': KeyValue });

but that does not seem to do anything. Can anyone help?


Solution

  • After doing some research I ended up using the following service:

    .service('MyService', function() {
      // Create a reference to ourself
      var sv = this;
    
      // Initialise the data structure
      sv.data = { };
    
      // Function to set an item in the map
      sv.setItem = function(key, value) {
        sv.data[key] = value;
      }
    
      // Function to retrieve a value from the map
      sv.getItem = function(key) {
        if (sv.data[key] != undefined) {
          return sv.data[key];
        }
        return false;
      }
    })