首页 > 解决方案 > 在 AngularJS 中只更新另一个数组中的一个数组值

问题描述

我通过 MongoDB 的两个不同功能和服务获得了两个数组。

一个数组 (rolesList) 用于填充选择框,另一个 (userList) 用于填充表格。问题是从其中获得最后一个数组的集合只有角色 id,我需要将角色名称打印到表中,因为我已经有了数据,我需要一种从角色列表数组中获取角色名称的方法和用它更新 userList.role。

最好的方法是什么?
我留下一个代码片段,希望您能更好地理解我的问题。

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.userList = [ { _id: 'ae21e1f0663dddf0c6e5e8b',
    fullname: 'Cosme Fulanito',
    lastname: 'Fulanito',
    lastname2: '',
    email: 'cosme.fulanito@mail.com',
    role: 'ADMIN_APPLICANT_PROFILE', //this is the _id on rolesList and I need to print the name
    name: 'Cosme' },
  { _id: 'ae21e4b0663dddf0c6e5e8d',
    fullname: 'Benito Camelo',
    lastname: 'Camelo',
    lastname2: '',
    email: 'benito.camelo@mail.com',
    role: 'PURCHASER_PROFILE',
    name: 'Benito' } ]


$scope.rolesList = [ {
_id: "ADMIN_APPLICANT_PROFILE",
name: "Administrador solicitante"
},
{
_id: "PURCHASER_PROFILE",
name: "Comprador" } ]

   
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>

    <div class="request-table-overflow">
      <table class="table m-b-none">
        <thead>
          <tr>
            <th>#</th>
            <th>Usuario</th>
            <th>Tipo de Cuenta</th>
            <th>Nombre</th>
            <th>Apellido</th>
            <th></th>
          </tr>
        </thead>
        <tbody ng-app="myApp" ng-controller="myCtrl">
          <tr ng-repeat="row in userList" st-select-row="row">
            <td class="text-muted"><span class="badge bg-black">{{$index +1}}</span></td>
            <td>{{row.email}}</td>
            <td>{{row.role}}</td> <!--This need to be updated to display the value of rolesList.name-->
            <td>{{row.name}}</td>
            <td>{{row.lastname}}</td>
            <td>
              <h5 ng-click="details(row._id)">
                             <span class="text-muted">Ver detalle </span>
                             <i class="fa fa-chevron-right" aria-hidden="true"></i>
                           </h5>
            </td>
          </tr>
        </tbody>

      </table>
    </div>

标签: arraysangularjs

解决方案


对于这种情况,我个人的方法是将对象用作字典。

为此,您可以将您的更改rolesList为如下所示:

$scope.rolesList = {
    "ADMIN_APPLICANT_PROFILE": "Administrador solicitante",
    "PURCHASER_PROFILE": "Comprador" 
}

然后在您的表格行中,您可以使用角色值引用角色名称

<td>{{ rolesList[row.role] }}</td>

如果您无法更改角色列表的格式,您可以使用以下循环创建字典

$scope.roleListDict = {};
angular.forEach($scope.rolesList, function(role, roleIndex) {
    $scope.roleListDict[role._id] = role.name;
});

<td>{{ roleListDict[row.role] }}</td>

推荐阅读