Angularjs 在Angular JS中存储键值对的最佳方式是什么

Angularjs 在Angular JS中存储键值对的最佳方式是什么,angularjs,angularjs-scope,angularjs-service,Angularjs,Angularjs Scope,Angularjs Service,我有一个由主页和部分页面组成的angular应用程序。部分页面显示在ui视图中 <div class="" ui-view> </div> 并尝试使用以下方法从部分页面控制器填充它: $scope.$parent.my_array.push({ 'KeyId': KeyVariableID, 'KeyValue': KeyValue }); 但这似乎没有任何作用。有人能帮忙吗?$rootScope可以工作,但我发现在跟踪其上设置的属性的来源时会有点混乱 相反,服务

我有一个由主页和部分页面组成的angular应用程序。部分页面显示在
ui视图中

<div class="" ui-view>

</div>
并尝试使用以下方法从部分页面控制器填充它:

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

但这似乎没有任何作用。有人能帮忙吗?

$rootScope
可以工作,但我发现在跟踪其上设置的属性的来源时会有点混乱

相反,服务可以用来保存状态。如果您有一个服务是某个状态(键值)对象的唯一真实来源,则无需担心继承某些$rootScope属性或父控制器属性

依靠内置的
$cacheFactory
提供商,您的服务可能看起来像:

angular.factory('myCache', function myCacheFactory($cacheFactory) {
  return $cacheFactory('my-cache');
}

现在,您可以将
myCache
服务包含在任何控制器中,并按照
$cacheFactory
文档中的说明使用它:

在进行一些研究后,我最终使用了以下服务:

.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;
  }
})

使用服务跨应用程序的各个部分共享数据和方法使用角度服务跨应用程序共享数据。yourAppModule.service('shareDataService',function(){//setter&&//getter method define here});是它是内置的通用存储服务,具有一些简单的功能。当然,您可以构建自己的服务,但是为什么呢?但是我如何传入并设置服务中的值呢?
.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;
  }
})