使用ng-model在下拉列表中使用ng-repeat和ng-options标记所选项目

时间:2017-11-24 08:12:40

标签: javascript angularjs

我想要实现的是在行中打印有关在该服务器上授予的服务器和权限的信息。为此,我使用数组displayServers来存储可以选择的服务器阵列,并在ng-repeat的每次迭代中创建一个包含这些服务器的下拉列表。我还希望在每次迭代中使用ng-model标记所选服务器,该服务器对应于JS对象,该对象存储有关服务器和授予的相应权限的信息。

使用服务器和权限存储信息的对象如下所示:

var modalUser = {
       Permissions: {
            server1: ['admin', 'developer'],
            server2: ['developer'],
            serverN: ['permissionN'] 
       }
}

var displayServers = [
     ['server1', 'server2', 'serverN'],
     ['server1', 'server2', 'serverN']   
]

HTML看起来像这样

   <tr ng-repeat="serverArray in displayServers track by $index" ng-if="server[0] != 'removed'">
        <td class="col-md-2">
        <div style="margin-top: 8px" >
            <select class="selectpicker server"
                    ng-options="serverName as serverName for serverName in serverArray track by serverName"
                    ng-model="modalUser.Permissions[serverName]">
            <option style="display: none" value="">Select server</option>
            </select>
        </div>
        </td>

2 个答案:

答案 0 :(得分:1)

在我看来,您可以将ng-model设置为simple属性,然后调用ng-change上的函数来执行逻辑,即通过代码设置“modalUser.Permissions [serverName]”。

希望有所帮助!

<强>已更新

    $scope.checkIfPresentInPermissions = funtions(serverName){
    // logic to check if server name is present in modalUser.Permissions[serverName]
    };



      <tr ng-repeat="serverArray in displayServers track by $index" ng-if="server[0] != 'removed'">
        <td class="col-md-2">
        <div style="margin-top: 8px" >
            <select class="selectpicker server"                   
                    ng-model="modalUser.SelectedServer">
            <option style="display: none" value="">Select server</option>

<option  ng-repeat="serverName as serverName for serverName in serverArray track by serverName" value="{{serverName }}" selected="checkIfPresentInPermissions(serverName)" >{{serverName }}</option>

            </select>
        </div>
        </td>

答案 1 :(得分:0)

感谢Danish您向我展示了解决问题的方法。我做的是:

      <tr ng-repeat="(key, value) in modalUser.gS_Permissions track by key">
          <td class="col-md-2">
              <div style="margin-top: 8px" >
                  <select class="selectpicker server">
                       <option style="display: none" value="">Select server</option>
                       <option ng-repeat="server in servers track by server"
                               value="{{server}}"
                               ng-selected="checkIfPresentInPermissions(server, key);">{{server}}</option>
                  </select>
              </div>
          </td>
      </tr>

checkIfPresentInPermissions(server)看起来像这样

 $scope.checkIfPresentInPermissions = function(server, key){
        return server === key;
    }