5

I created a directive to display data. I can include it in an ng-repeat and see that the model is connected. When I click away and return the page, the data is displayed again with previously made changes. I used ngResources to load the data from an API. So far, so good: it works as expected.

Here's the part that breaks: if I save the data to the API in my directive, the item disappears from the page (more specifically, it's drawn with its fields blank). The rest of the items remain as before. Only the saved one changes.

Here's the directive:

.directive('action', function() {
    return {
        restrict: 'E',
        scope: {
            data:'=model'
        },
        templateUrl: 'modules/actions/view.tpl.html',
        replace: true,
        link: function(scope, element, attr) {
            scope.save = function() {
                console.log(" data to save:" + JSON.stringify(scope.data));
                scope.data.$save();
            }
        }
    };
})

The html associated with the directive includes:

<p><input type="text" ng-model="data.assignee" ng-change="save()">

Here's how the directive used:

<div ng-repeat="item in data">
  <action model="item" />
</div>

Here's a fiddle that shows additional context. You can see the basic directive working with some fake data. The code for the API call is commented out.

Again, the problem occurs when the scope.data.$save(); line is uncommented. When the item displayed in the ng-repeat tries to save itself, it disappears from the displayed list of items, replaced by one with blank fields. When I reload the whole application, I see that the API save succeeded and the item now displays correctly.

What I suspect is happening is that the save call operates on the correct item but somehow replaces the changed item with a new, blank one, perhaps due to prototypal inheritance. The save then causes an update to the parent scope, which redraws the list and shows the new blanked item.

Can someone clarify what is happening and how to fix it?

4

1 回答 1

4

我认为您会发现对您的$save()命令的 HTTP 响应正在返回空数据。

这是如何$resource工作的。当您调用$save()时,它将(默认情况下)使用 HTTP POST 调用您的 REST 服务。响应应该是资源的服务器状态。然后将结果复制到您的对象。在这种情况下,我猜测您的 REST 服务正在返回一个空对象。

换句话说,如果您发送一个正文为 的 POST {name: 'foo'},您希望来自服务器的响应类似于{id: 44, name: 'foo', extraInfoServerCreated: 'bar'}.

于 2013-09-05T00:46:48.397 回答