矩形反应和ng重复 [英] Restangular response and ng-repeat

查看:93
本文介绍了矩形反应和ng重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始学习使用restangular与我的restfull API(风帆)进行对话.我偶然发现的问题是,在更改作用域中的列表之后,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.

控制器:

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);
    });
}
}]);

服务:

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

模板:

<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.

预先感谢

推荐答案

AngularJS(和javascript)关心引用与覆盖.为了安全起见,我总是始终先设置范围变量,然后使用angular.copy()Restangular.copy()(如果正在设置的是Restangular对象)进行更新.

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.

(请注意,我将s重命名为传统" $scope,以便于其他所有人阅读)

(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);
    });
}
}]);

这篇关于矩形反应和ng重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆