简体   繁体   中英

AngularJS - Nested ng-repeat for table

I just started with AngularJS and I'm trying to make a users table that shows the users for the application and the roles they are in (eg Admin, Editor, Anon) with checkboxes to take the users in and out of roles.

<tbody>
    <tr data-ng-repeat="item in pagedItems[currentPage] | orderBy:sortingOrder:reverse">
        <td class="table-item-title"><a title="{{item.UserName}}" href="" ng-click="loadEditForm(item.UserName)">{{item.UserName}}</a></td>
        <td class="hmax479">{{item.Email}}</td>
        <td align="center" data-ng-repeat="role in roles" style="align:center;">
             <input type="checkbox" data-ng-model="role.IsChecked" style="align:center;"/>
        </td>
    </tr>
</tbody

With the above code it updates the checkboxes for the entire group based on the last user that was clicked rather than for a single user. Is there any way I can change this code with something like a "user in users" ng-repeat to change this or do I need to add a new function in the controller?

Each user could have an array of roles to show the roles that has been assigned to the user. For each user, while looping through the roles, you use a filter to only check assigned roles. You could use a function in your controller to add/remove roles as the check boxes are selected/deselected.

<tbody>
  <tr data-ng-repeat="item in pagedItems[currentPage] | orderBy:sortingOrder:reverse">
    <td class="table-item-title"><a title="{{item.UserName}}" href="" ng-click="loadEditForm(item.UserName)">{{item.UserName}}</a></td>
    <td class="hmax479">{{item.Email}}</td>
    <td align="center" data-ng-repeat="role in roles" style="align:center;">
         <input type="checkbox" data-ng-checked="role | hasRole:item.Roles" data-ng-click="addOrRemove($parent.$index, role)" style="align:center;"/>
    </td>
  </tr>
</tbody>

The filter

app.filter('hasRole', function() {
    return function (role, userRoles) {
        var result = false;
        userRoles.forEach(function(value, index) { // loop through the roles
            // return true if the user has the role
            if(role.Name == value.Name) // This is replaced by any method of comparing roles 
               result = true;
        });
        return result;
    }
}

In your controller, you implement addOrRemove()

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