Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Items disappear when saved

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?

like image 296
CodeGuy2001 Avatar asked Oct 03 '22 01:10

CodeGuy2001


1 Answers

I think that you are going to find that the HTTP response to your $save() command is returning empty data.

This is how $resource works. When you call $save(), it will (by default) call your REST service with a HTTP POST. The response is expected to be the server state of the resource. The result is then copied to your object. In this case, I am guessing that your REST service is returning an empty object.

In other words, if you send a POST with a body of {name: 'foo'}, you expect the response from the server to be something like {id: 44, name: 'foo', extraInfoServerCreated: 'bar'}.

like image 132
Brian Genisio Avatar answered Oct 07 '22 18:10

Brian Genisio