【问题标题】:What is the best way to store key value pairs in Angular JS在Angular JS中存储键值对的最佳方法是什么
【发布时间】:2017-02-22 16:23:11
【问题描述】:

我有一个由主页和部分页面组成的 Angular 应用程序。部分页面显示在ui-view

<div class="" ui-view>

</div>

为了存储一个全局变量,我使用$scope.$parent.variable_name。所以我在基本控制器中声明了变量:

$scope.$parent.my_array = [];

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

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

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

【问题讨论】:

  • 使用服务在应用程序的各个部分共享数据和方法
  • 使用 Angular 服务在应用程序之间共享数据。 yourAppModule.service('shareDataService', function(){ // setter && // getter 方法在这里定义 });
  • $cacheFactory 是。它是具有一些简单功能的内置通用存储服务。当然,您可以构建自己的服务,但为什么呢?

标签: angularjs angularjs-scope angularjs-service


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    依靠内置的$cacheFactory 提供程序,您的服务可能如下所示:

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

    现在,您可以在任何控制器中包含 myCache 服务并按照 $cacheFactory 文档中的说明使用它:https://docs.angularjs.org/api/ng/service/$cacheFactory

    【讨论】:

    • 但是如何在我的服务中传入和设置值?
    猜你喜欢
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 2020-02-03
    • 2012-10-23
    • 2012-05-04
    • 2011-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多