Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restangular response and ng-repeat

I have recently started to learn angularjs using restangular to talk to my restfull API (sails). The problem I have stumbled upon is that the ng-repeat does not update after I change the list in the scope.

Controller:

app.controller('UsersCtrl', ['UsersSvc', '$scope', function(UsersSvc, s) {
    UsersSvc.getList().then(function (new_users) {
        s.users = new_users;
    })
    s.destroy = function (user) {
        user.remove().then(function () {
        s.users = _.without(s.users, user);
    });
}
}]);

Service:

app.factory('UsersSvc', function(Restangular) {
    return Restangular.all('users');
});

Template:

<div ng-controller="UsersCtrl">
    ...
    <tr ng-repeat"user in users">  
          <td>{{user.firstName}}</td>  
          <td>{{user.lastName}} </td>  
          <td>{{user.emailAddress}}</td>  
          <td>{{user.age}}</td>  
    </tr> 
    ...
</div>

When I inspect the scope the array of restangular objects is correctly assigned to the scope of the users controller but the template refuses to update.

Thanks in advance

like image 998
rtemperv Avatar asked Sep 30 '22 22:09

rtemperv


1 Answers

AngularJS (and javascript) care about references vs. overwrites. So to be safe I always set my scope variables initially, and then update using angular.copy() or Restangular.copy() (if it's a Restangular object being set).

Below is how I'd refactor your controller to ensure bindings + digest cycles stay connected.

(Please note I renamed s to the "traditional" $scope for easier reading for everyone else)

app.controller('UsersCtrl', ['$scope', 'UsersSvc', 'Restangular', function($scope, UsersSvc, Restangular) {

    // we're expecting a list, so default as array
    $scope.users = [];

    UsersSvc.getList().then(function (new_users) {
        // In normal $resource/ng projects use: angular.copy(src, dst) but
        // Restangular has an issue when using angular.copy():
        // https://github.com/mgonto/restangular/issues/55
        // so use their version of copy():
        Restangular.copy(new_users, $scope.users);
    });

    $scope.destroy = function (user) {
        user.remove().then(function () {
        $scope.users = _.without($scope.users, user);
    });
}
}]);
like image 52
electblake Avatar answered Oct 03 '22 11:10

electblake