0
votes
<ul class="users">
   <li ng-repeat="user in users">
       <p>{{user.name}} {{user.email}}</p>
   </li>
</ul>

I am working on an CRUD view using AngularJS, and back-end API is on users collection. On the view side, I have a newUser object and each field has ng-model for 2-way data binding. On the Save click button, I call a "saveClickHandler()" function in the controller. I am making a POST to an User API to save the user data. However I have a list view which populates the user collection at the controller start and displays the users.

How to refresh the user collection after the save user?

let add = function() {
        console.log("In add method");
        $http.post('api/user', {"name": $scope.newUser.name, 
        "email": $scope.newUser.email})
        .then(function(result){
            $scope.newUser = {};
        }, function (error){
          console.log(error, 'can not get data.');
        });
      }
<p>
<label>Name</label>
<input type=“text” ng-model="newUser.name"/>
<label>Email</label>
<input type=“email” ng-model="newUser.email"/>
</p>
1
You just need to fetch the users again from the server, make a get request and store the results in $scope.users - Alon Eitan

1 Answers

0
votes

You can just call $route.reload(), if your controller already fetchs the result of all users when the page loads:

let add = function() {
    console.log("In add method");
    $http.post('api/user', {"name": $scope.newUser.name, 
    "email": $scope.newUser.email})
    .then(function(result){
        $route.reload();
    }, function (error){
      console.log(error, 'can not get data.');
    });
  }