简体   繁体   中英

AngularJS $resource | don't update view until promise resolved

I am wanting to use $resource to make a RESTful update on our server but the view get's updated as soon as the user clicks when I would like it to not update until the server sends a response. I am using a controller with a service layer that uses a rest resource.

Template:

<tbody>
    <tr ng-repeat="user in users">      
        <td><button class="radius tiny button" 
                ng-click="toggleUserActive(user)" 
                ng-bind="user.active ? 'Disable User' : 'Enable User'">
            </button>
        </td>
    <tr>
</tbody>

Controller:

angular.module('admin', ['admin.AdminService'])

  .controller('adminCtrl', function ($scope, adminService) {

    $scope.toggleUserActive = function(user){
      adminService.toggleUserDisabled(user).then(function(response){
        // Want the update to happen here
        user.active = response;
      });
    };

  });

Service:

angular.module('admin.AdminService', ['rest'])

  .service('adminService', function AdminService(UserRest){

    this.toggleUserDisabled = function(user) {
      user.active = !user.active;
      return UserRest.update(user).$promise.then(function(result){
        return result.active;
      });
    };

  });

Rest service:

angular.module('rest', ['config','ngResource'])

  .factory('RestEndpoint', function (apiEndpoint) {
    return {
      users: apiEndpoint + '/admin/users/:username'
    };
  })

  .factory('UserRest', function ($resource, RestEndpoint){
    return $resource(RestEndpoint.users, {username:'@username'},{
      update: {
        method: 'PUT'
      }
    });
  });

How can I code this where the view does not update until response has made it back?

You could use something like this in your view

ng-show="user.active"

which will show once the $scope is updated with that new data.

I have not used the rest service as you are at the moment, but doing something similar with API calls, I used the $q and promises. Can you use the $q and promises in the controller, so the controller codes does not continue until the responses are received?

.controller('MyController', function($scope, $http, $q) {
    var JSON1 = $http.get('example1.json');
    var JSON2 = $http.get('example2.json');

    $q.all([JSON1, JSON2]).then(function(results) {
        ...
    });
})

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