如何将对象推送到数组列表?

时间:2016-12-19 17:03:09

标签: javascript angularjs

调用方法addValue后我想将selectedUsers对象值添加到数组列表中,AngularJs的新手是否有更好的方法可以使用AngularJs实现它?

main.html中

<tr ng-repeat="user in userList track by $index">
          <td st-ratio="20">{{user.attuid}}</td>
          <td st-ratio="30">{{user.firstName}} {{user.lastName}}</td>
          <td st-ratio="15" ng-bind-html="user.type"></td>
          <td st-ratio="15">{{user.email}}</td>
          <td><input type="checkbox" ng-model="user.selected" ng-click="addValue(user)"> </td>
          <!--<td st-ratio="20" class="text-right">
            <button type="button" ng-click="editUser($index, user)" class="btn btn-primary">
              Approve
            </button>
          </td>-->
        </tr>

ctrl.js

var selectedUsers = {
    attuid: '',
    firstName: '',
    lastName: '',
    email: ''
};

$scope.addValue = function(user) {
    $scope.selectedUsers = $scope.selectedUsers || [];
    $scope.selectedUsers.push({
        attuid: $scope.user.attuid,
        firstName: $scope.user.firstName,
        lastName: $scope.user.lastName,
        email: $scope.user.email
    });


};

1 个答案:

答案 0 :(得分:1)

您没有引用正确的变量: 这是你的代码:

$scope.addValue = function(user) {
    $scope.selectedUsers = $scope.selectedUsers || [];
    $scope.selectedUsers.push({
        attuid: $scope.user.attuid,
        firstName: $scope.user.firstName,
        lastName: $scope.user.lastName,
        email: $scope.user.email
    });


};

您没有使用用户变量:

$scope.selectedUsers = $scope.selectedUsers || [];
$scope.addValue = function(user) {
    $scope.selectedUsers.push({
        attuid: user.attuid,
        firstName: user.firstName,
        lastName: user.lastName,
        email: user.email
    });


};

除此之外,我看到你正在使用一个复选框。所以我猜你只想在选中复选框时才推送用户。要做到这一点,您必须检查用户是否已经在数组中,如果未选中该复选框,则将其删除。此代码不完整