AngularJS:在$ resource POST和$ scope更新后,Repeater不会更新

时间:2015-02-09 13:19:16

标签: angularjs angularjs-scope angularjs-ng-repeat angular-resource

将许多google结果链接变为紫色。我发现自己很难过。

我设置了一个$资源,用于与我设置的contacts api端点进行交互(Laravel后端)。查询页面上显示的初始联系人工作得很好。我甚至可以发送要创建的新联系人,但是在发送POST请求以创建新联系人后,联系人不会更新。

联系控制器      var contactCtrl = angular.module(' contactCtrl',[' ngResource']);

    contactCtrl.controller('contactController', ['$scope', '$http', 'Contact', 'ContactRest', 'routeBase', function($scope, $http, Contact, ContactRest, routeBase) {

        $scope.contacts = [];
        // $scope.contacts is updated with all of the contacts for /activity/1
        ContactRest.getResource({'resource_type' : 'activity', 'resource_id' : '1'}, function(contacts) {
            $scope.contacts = contacts;
        }, function() {
            console.log('contacts loading failed');
        });


        $scope.contact = new ContactRest();

        // Action to send a request to create a new contact for /activity/1
        $scope.add = function(contact, resource_type, resource_id) {

            console.log('submitting the contact: ', contact);
            contact.$add({ 'resource_type' : resource_type, 'resource_id' : resource_id });

            $scope.contacts.push(contact);
            console.log('current contacts in scope are', $scope.contacts);
            $('#contactModal').modal('hide');

        }
    }]);

联系Restful Service

  .factory('ContactRest', ['$resource', '$location', function($resource, $location) {
    var host = $location.host()
    baseUrl = 'http://' + host;

  return $resource('http://' + host + '/api/contact', { }, {
    // Get all contacts belonging to a resource
    getResource : { 
        method : 'GET', url : 'http://' + host + '/api/:resource_type/:resource_id/contact', 
        params : {'resource_type' : '@resource_type' , 'resource_id' : '@resource_id' },
        isArray: true,
    },
    // Add a contact to a resource
    add: { 
        method : 'POST', 
        url : baseUrl + '/api/contact/add/:resource_type/:resource_id',
        params : {'resource_type' : '@resource_type', 'resource_id' : '@resource_id'} }
  });
}]);

发送请求后,$ scope会更新。我已经多次测试了它。看起来视图中的转发器不会随着控制器中更新的$ scope.contacts而改变。我有什么遗失的吗?

2 个答案:

答案 0 :(得分:2)

这可能是因为您的$add函数是async ajax调用。这意味着您只能在使用$scope.contacts.push(contact); json的服务器响应后调用contact

callback功能的 $add 事件中尝试推送。

e.g。

...
add: { 
            method : 'POST', 
            url : baseUrl + '/api/contact/add/:resource_type/:resource_id',
            params : {'resource_type' : '@resource_type', 'resource_id' : '@resource_id'} }
      }, callback_function_here);
...

为了使其可重用,请在函数调用期间传递回调,例如

contact.$add({ 'resource_type' : resource_type, 'resource_id' : resource_id }, 
    function (response) {
        $scope.contacts.push(response);
    }
);

答案 1 :(得分:0)

问题在于我使用了同一控制器的2个不同实例。显然,这会创建两个不同的范围。控制器/资源中的所有内容都正常工作,这是一个实现问题。

相关问题