首页 文章

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

提问于
浏览
7

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

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

我正在使用foreach迭代它们,如下所示,输出正如预期的那样

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

                });

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

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

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

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

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

但我的服务器期待像

"Content-Type" => "application/x-www-form-urlencoded"

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

3 回答

  • 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>
    
  • 0

    您可以使用 :

    [...headerObj][...headerObj.entries()] 得到两个维数组 . 并迭代它们 .

    [...headerObj.keys()][...headerObj.values()] 为常规数组 .

  • -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>
    

相关问题