angularjs – Restangular响应和ng-repeat
发布时间:2020-12-17 10:26:42 所属栏目:安全 来源:网络整理
导读:我最近开始学习 angularjs使用restangular与我的restfull API(sails)交谈.我偶然发现的问题是,在更改范围中的列表后,ng-repeat不会更新. 控制器: app.controller('UsersCtrl',['UsersSvc','$scope',function(UsersSvc,s) { UsersSvc.getList().then(functio
我最近开始学习
angularjs使用restangular与我的restfull API(sails)交谈.我偶然发现的问题是,在更改范围中的列表后,ng-repeat不会更新.
控制器: 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> 当我检查范围时,restangular对象数组被正确地分配给用户控制器的范围,但模板拒绝更新. 提前致谢
AngularJS(和javascript)关心引用和覆盖.所以为了安全起见,我总是先设置我的范围变量,然后使用angular.copy()或Restangular.copy()进行更新(如果它是一个设置的Restangular对象).
下面是我如何重构你的控制器以确保绑定摘要周期保持连接. (请注意我将s重命名为“传统”$scope,以方便其他人阅读) 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); }); } }]); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |