如何使用角度ng-repeat来迭代javascript Map

时间:2014-12-20 17:16:39

标签: javascript angularjs angularjs-ng-repeat

我正在开发一个Angualr应用程序,我们有一个Map对象(如下所示)。地图对象(headerObj)的关键和值来自用户作为应用程序的输入,

  var headerObj = new Map();
  headerObj.set(key,value);

我使用foreach迭代它们,如下所示,输出按预期进行

           $scope.inputHeaders.forEach(function (headerkey, headervalue) {
                     console.log(headerkey, headervalue; 

                });

但是我必须在UI中显示这个地图值,用户可以再次编辑,所以我将它们绑定了

          <li class="list-group-item" ng-repeat="header in inputHeaders">
              <div ng-repeat="(key, value) in header">
                  {{key}} : {{value}}
             </div>
          </li>

我用google搜索并尝试了几种方法,但没有任何帮助,所以我基本上想知道如何使用forEach以角度迭代地图?

为了更清晰,我的要求是这样的:我需要将值作为键,值对传递给服务器,只有在我没有错的情况下,假设我使用对象属性是关键的对象将被修复如

       {"key":"Content-Type","value":"application/x-www-form-urlencoded","$$hashKey":"003"}]

但是我的服务器期待像

这样的东西
        "Content-Type" => "application/x-www-form-urlencoded"

创建了一个plunkr edit http://plnkr.co/edit/t2g6Dl831HGyjD6uSdf3?p=preview

3 个答案:

答案 0 :(得分:0)

AngularJS 1.x不知道如何使用Javascript迭代器,因此您必须先使用Array.from()将Map对象转换为数组。

控制器:

$scope.inputHeadersArray = Array.from($scope.inputHeaders);

查看:

<li class="list-group-item" ng-repeat="header in inputHeadersArray">
  {{header[0]}} : {{header[1]}}
</li>

答案 1 :(得分:0)

您可以使用:

[...headerObj][...headerObj.entries()]得到二维数组。并对其进行迭代。

[...headerObj.keys()][...headerObj.values()]用于常规数组。

答案 2 :(得分:-2)

此处代码中的更改很少。 http://plnkr.co/edit/gpc1mPsZrl2QVXbnWZKA?p=preview

app = angular.module('testDemo', []);

app.controller('submitCtrl',function($scope) {
 $scope.header={};
 $scope.inputHeaders=[];

 $scope.addHeader = function() {

 $scope.inputHeaders.push($scope.header);
 $scope.header = {};
 $scope.header.key='';
 $scope.header.value='';

}

$scope.log=function(){
 //alert('in log');
 $scope.inputHeaders.forEach(function (key, value) {
 console.log(key, value);
});
}
});

HTML:

<body ng-controller='submitCtrl'>
<div >

<input type="text"  class="=form-control" ng-model="header.key" placeholder="Key">
<input type="text" class="=form-control" ng-model="header.value" placeholder="value">
<button class="btn btn-sucess" ng-click="addHeader()">Add</button>
<button class="btn btn-sucess" ng-click="log()">Log</button>
<div>
<ul class="list-group">
<li class="list-group-item" ng-repeat="header in inputHeaders">


 <!-- need to to work on this logic -->
 <div ng-show="inputHeaders.length>=1">
 <input type="text"   ng-model="header.value" />
 <input type="text"   ng-model="header.key" />
 </div>

</li>
</ul>            
</div>

</div>
</body>