문제

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

도움이 되었습니까?

해결책

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);
    });
}
}]);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top