user3055606
user3055606

Reputation: 65

AngularJS: Get selected Item

I have an ng-repeat that display users in rows, when a user is clicked, it open modal popup for edit User containing all user details. When I select another role for the user and tries to get the newly selected row so as to pass to http put, it does not give the newly selected item text instead it still return the old text

//display users in table rows, click on username to edit

    <tr ng-repeat="item in usersData | filter: searchBox">

        <td><a ng-click="openEditUser($index)">{{item.UserName}}</a></td>
        <td>{{item.EMail}}</td>
        <td>{{item.RoleName}}</td>
        <td style="text-align: right;">{{item.IsActive ? 'Yes' : 'No'}}</td>

 </tr>

When the modal popup opens, I get all the roles from API and add it to <select> field

//get all roles and add to select field

$http.get('mydomain.com/api/Users/GetAllRole').then(function (response) {
            $rootScope.myData = {};
            $rootScope.myData = response.data;
        });

// Here ng-model="selectedItem.RoleId"

<select ng-required="true" ng-model="selectedItem.RoleId" class="form-control"
                ng-options="item._id as item.RoleName for item in myData">
            <option value="">Select</option>                                


</select>

Here when I choose another role for the user in the <select> field and try to get $scope.selectedItem.RoleId it gives the new selected RoleId but when I try to get $scope.selectedItem.RoleName from the <select> field it doesn't give the new selected item instead it still returns the old selected item

$scope.EditUser = function(){

    $http.put("domain.com/api/Users/UpdateUser", {
       _id: $scope.selectedItem._id,'RoleId': $scope.selectedItem.RoleId, 'EMail': $scope.selectedItem.EMail, RoleName : $scope.selectedItem.RoleName, IsActive: $scope.selectedItem.IsActive

    }).then(function (response) {
        $route.reload();
        $scope.ok();
        $scope.simpleSuccess();
    }, function (error) {
        $scope.ok();
        $scope.simpleError();
    });


  };

Upvotes: 0

Views: 2058

Answers (1)

Erazihel
Erazihel

Reputation: 7605

I think that this is due to the wrong ng-modelgiven to your ng-repeat. The model used here is selectedItem.RoleId.

Angular will only update the RoleId field of your object instead of the whole object. You should set the ng-model to selectedItem.

<select ng-required="true" ng-model="selectedItem" class="form-control" ng-options="item._id as item.RoleName for item in myData">
    <option value="">Select</option>                                
</select>

Unfortunately, you didn't provide any JSFiddle so I can't check that this is actually the source of the problem.

EDIT

To have the old role selected, you have to set it to the corresponding entrance of the array returned by the API.

I created this JSFiddle so you can see how to properly use the ng-select directive.

Upvotes: 1

Related Questions