简体   繁体   中英

ng-Repeat=“(key,val)” not working for table in Angular

i am working on a MEAN stack application. I am fetching values from database, creating a Map using $scope.varMap = new Map(); in my controller and trying to show the key,value of varMap in my angular UI using following code:

This is how I am setting value in controller:

 $scope.varMap.set($scope.mappings.name,$scope.mappings.shortname);

and this is code snippet from angular:

   <table class="table table-bordered table-list">
        <thead>
           <tr>
             <th>KEY</th>
             <th>VALUE</th>
           </tr> 
        </thead>
        <tbody>
           <tr ng-repeat="(key,val) in varMap">
              <td>{{key}}</td>
              <td>{{val}}</td>
           </tr>
        </tbody>
</table>

but unfortunately the ng-repeat is not showing anything. I tried printing the map values in console in my controller and its printing proper values.

     for (var [key, value] of $scope.varMap) {
        console.log(key + ' = ' + value);
     }

I tried the links & answers available on stackoverflow but no success. Please help.

Since ng-repeat not support Map iteration, you could use a custom filter fromMap like below :

app.filter('fromMap', function() {
  return function(input) {
   var out = {};
   input.forEach((v, k) => out[k] = v);
   return out;
 }
});

and your controler :

app.controller('MainCtrl', function($scope) { 
  $scope.data = new Map(); 
  $scope.data.set("prop1","as"); 
  $scope.data.set("prop2","ssas"); 
});

and your HTML:

  <body ng-controller="MainCtrl">
   <table>
    <tr ng-repeat="(key, val) in data | fromMap"><td>{{key}}</td><td>{{val}}</td></tr>
   </table>
  </body>

Here is a working demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM