AngularJs duplicating (briefly) ng-repeat list when making new inserts in the bank

6

I'm working with an application where in a view I own the product register of a company, or its clients, suppliers, etc. Each view serves a specific area, however each view works with various data and data flow, such as adding new items, deleting and updating.

The problem I noticed is that when view has many items, when executing an addition, where it is necessary to reload of the list, in order to insert the new data with its respective id of the database, there is a "duplicate" of the whole list for a brief moment. Generally speaking, I enter a new client, it does the reload of the list, applies the whole list to the end of the list that is already in view to only then remove the old list.

The code I am using has no secret, has $http simple of POST and GET (my backend is controlled by PHP ) as in the example:

ctrl.js

//Chamada automática
    function getProduto() {
        factProdutos.getProdutos().then(function (res) {
            vm.produtos = res;
        }); 
    };

//Chamada da view
    vm.addProduto   = addProduto;

//Function - Produtos
    function addProduto(id) {
        var data = {id_empresa:id};
        $http.post('php/mainFile.php?action=addProduto', data).then(
            function(res) { getProduto(); },
            function(err) { alert(feedbackError); }
        );
    };

factory.js

function _getProdutos() {
    return $http.get("php/getFile.php?action=getProduto").then(
        function(res) { return res.data;},
        function(err) {alert(feedbackError);}
    );  
};

To do the deletion or update is not a problem, because I do the process in the Database without needing to reload the information, AngularJs will take care of doing this in the view. The same thing happens to remove a product from the list, I only use $filter and I delete the element from the array.

The problem occurs even when doing a new insertion, because I need the id to perform future processes. I've read about using the same $ filter logic for deletion, but instead of removing, add the new die.

But how to identify the new data? Or compare the new list loaded with the list that is currently in my view ? Or is this the best way to do this optimization, or is there a better method?

This is not an error, but an optimization of the data flow.

    
asked by anonymous 25.11.2015 / 01:44

1 answer

4

One of the possible ways to avoid this artifact (content duplication) is to use a service to manage your collections, and use an observer pattern to receive update notifications.

(This demo generates content on the console, in Chrome, use F12 to open development tools and track content.)

The steps would be as follows:

  • Implement Factories to access your application's REST endpoints (one for collection, one for individual items).
  • Implement a service that consumes the two Factories mentioned above, store the results of operations and coordinate CRUD operations;
  • Allow consumers to subscribe to receive updates.

In the example below, the NyanJS library automatically generates the collections userCollectionFactory and userItemFactory , and consumes them in the service userDataService .

The controllers SampleController and SampleController2 , in turn, receive injection of userDataService service and subscribe for updates via register method. One allows the exclusion of objects with even id, and another of objects with odd id. The service coordinates operations and announces content changes.

If you need to generate more test entries, use the following URL: link

var app = angular.module('NyanNG', ['ngNyanStack']);

app
    .config([
        'nyanStackProvider', '$httpProvider',
        function ( nyanStackProvider, $httpProvider) {

            nyanStackProvider
                .setup({
                    RestPrefix: 'http://565515f70c4bde110041bfef.mockapi.io/data',
                    Authenticate: false,
                    PluralDescriptor: '{ScopeDescriptor}',
                })
                .module('user', {
                    RootPrefix: "data",
                    collectionName: 'User',
                    useLookupQuery: true,
                    useLocatorQuery: true,

                });

            $httpProvider.defaults.useXDomain = true;
            delete $httpProvider.defaults.headers.common['X-Requested-With'];
        }
    ]).run([
        'nyanStack', function (nyanStack) {
            nyanStack.start();
        }
    ]);
angular.module('ngNyanStack')
    .controller('SampleController', function ($scope, userDataService) {

        $scope.svc = userDataService;

        var localUpdate = function () {
            $scope.data = userDataService.data;
        };

        userDataService.register(localUpdate);

    })
    .controller('SampleController2', function ($scope, userDataService) {

        $scope.svc = userDataService;

        var localUpdate = function () {
            $scope.data = userDataService.data;
        };

        userDataService.register(localUpdate);

    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-resource.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.js"></script><scriptsrc="https://rawgit.com/bucknellu/Nyan/ffb7f828938ebeac31ea47f433064bd44552227c/Samples/REST/ng/res/nyan.js"></script>

<table ng-app="NyanNG">
  <tr>
    <td>
      <div ng-controller="SampleController">
        Controller 1

        <p ng-repeat="i in data">
          {{i.id}} - {{i.name}} <button ng-if="!(i.id % 2)" ng-click="svc.remove(i.id);">Delete</button>
        </p>


      </div>
    </td>
    <td>
      Controller 2
      
      <div ng-controller="SampleController2">

        <p ng-repeat="i in data">
          {{i.id}} - {{i.name}} <button ng-if="(i.id % 2)" ng-click="svc.remove(i.id);">Delete</button>
        </p>


      </div>
    </td>
  </tr>
</table>
    
25.11.2015 / 04:56