Update table with ng-repeat does not work

0

I have a table that is populated with a ng-repeat that iterates over a list of objects. The problem is that when the value of that list changes, the ng-repeat does not refresh the data. To the list I take it from a database through a $resource that I have in a service. I was told it could be because of a cache problem, so I modified the service so that in the query of $resource method it does not cache the data, but it still does not work.

I leave you the index.html :

<!DOCTYPE html>
<html ng-app="missingDog">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Missing Dog</title>
        <script src="resources/dependencies/angular.min.js"></script>
        <script src="resources/dependencies/angular-route.min.js"></script>
        <script src="resources/dependencies/angular-resource.min.js"></script>
        <script src="resources/app/js/app.js"></script>
        <script src="resources/app/js/Services/MascotaService.js"></script>
        <script src="resources/app/js/Controllers/MainController.js"></script>
        <script src="resources/app/js/Controllers/FormController.js"></script>
        <script src="resources/app/js/Controllers/ListController.js"></script>
        <link href="resources/dependencies/bootstrap.min.css" rel="stylesheet">
        <link href="resources/dependencies/bootstrap-theme.min.css" rel="stylesheet">
        <link href="resources/app/css/mystyles.css" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">
    </head>
    <body data-spy="scroll" data-target=".navbar" data-offset="50">
        <!-- HEADER -->
        <header class="page-header row-header">
            <div class="container-fluid row-header">
                <div class="row row-header well">
                    <!-- HEADER IMAGE -->
                    <div class="col-xs-1">
                        <img ng-src="resources/app/images/beagles.png" id="imgHeader" alt="Missing Dog" class="img-rounded img-responsive"/>
                    </div>
                    <!-- HEADER TITLE AND TEXT -->
                    <div class="col-xs-11">
                        <h1><a href="#home">Missing Dog</a></h1>
                        <p>
                            Missing Dog is a community that ensures support and charity towards stray dogs. 
                            It's a pleasure to help you find your lost pet!
                        </p>
                    </div>
                </div>
            </div>
            <nav class="navbar navbar-default row-header" role="navigation" data-spy="affix" data-offset-top="104.97">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-lg-2 navbar-header">
                            <a class="navbar-brand" href="#home">Missing Dog</a>
                        </div>
                        <ul class="col-lg-10 nav navbar-nav"> <!-- navbar-nav -->
                            <li class="active"><a data-toggle="pill" href="#home">Home</a></li>
                            <li><a data-toggle="pill" href="#form">Report a Missing Dog</a></li>
                            <li><a data-toggle="pill" href="#view">View the Missing Dogs</a></li>
                        </ul>
                    </div>
                </div>
            </nav>
        </header>

        <!-- MAIN CONTENT -->
        <div id="mainContent" class="container-fluid" ng-controller="MainController">

                <!-- HOME -->
                <section id="home" class="row row-content">
                    <div class="col-xs-offset-3 col-xs-7 well">
                        <div class="col-xs-6">
                            <img alt="Missing Dog 2" ng-src="resources/app/images/dog-brown.jpg" class="img-thumbnail img-responsive">
                        </div>
                        <div class="col-xs-6">
                            <p>
                                Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vel, repellendus. 
                                Quae enim, aspernatur odit beatae illo, placeat earum impedit magni veniam. 
                                Laboriosam aperiam esse eum dolorem amet ipsum sapiente odit. Lorem ipsum dolor sit amet, 
                                consectetur adipisicing elit. Mollitia soluta eaque velit? Quam quasi, at voluptate dicta dignissimos, 
                                quibusdam reiciendis, rem aut amet quos ut dolore blanditiis, doloremque velit mollitia! Lorem ipsum dolor 
                                sit amet, consectetur adipisicing elit. Animi minus inventore corporis quasi! Nam eius quos aut dolore 
                                quibusdam quis placeat, quia, inventore dolor amet, soluta molestiae mollitia dicta praesentium. Lorem ipsum 
                                dolor sit amet, consectetur adipisicing elit. Alias et impedit, natus fuga sit earum hic reiciendis 
                                cupiditate atque dignissimos aperiam magnam esse eum, quibusdam id illum facilis optio! Eaque. 
                                Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus veritatis natus sed ipsa, recusandae 
                                doloribus cupiditate, incidunt. Impedit nam rerum sed doloremque nisi quasi non dolores eius. Odit ad, 
                                repellat. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maiores odit, veniam magnam quia 
                                dignissimos itaque eos reiciendis labore quasi, architecto facere amet nobis blanditiis eveniet. 
                                Earum temporibus non doloribus ex.
                            </p>
                        </div>
                    </div>
                </section>

                <!-- FORM FOR REPORTING MISSING DOGS -->
                <section id="form" class="row row-content" ng-controller="FormController">
                    <div class="well col-xs-offset-3 col-xs-7">
                        <div class="col-xs-offset-4 col-xs-8">
                            <h1>Report a Missing Dog</h1>
                        </div>
                        <div class="col-xs-offset-1 col-xs-11"> <!-- col-xs-offset-1  -->
                            <form class="form-horizontal" name="mascotasForm" ng-submit="guardar()">
                                <div class="form-group">
                                    <label class="control-label col-xs-2" for="name">Name: </label>
                                    <div class="col-xs-8">
                                        <input class="form-control" name="name" type="text" required placeholder="Name of the dog" ng-model="mascota.nombre" /> <br/>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="control-label col-xs-2" for="race">Race: </label>
                                    <div class="col-xs-8">
                                        <input class="form-control" name="race" type="text" required placeholder="Race of the dog" ng-model="mascota.raza" /> <br/>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="control-label col-xs-2" for="description">Description: </label>
                                    <div class="col-xs-8">
                                        <input class="form-control" name="description" type="text" required placeholder="A little description" ng-model="mascota.descripcion" /> <br/>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="control-label col-xs-2" for="lostPlace">Place where pet has lost: </label>
                                    <div class="col-xs-8">
                                        <input class="form-control" name="lostPlace" type="text" required placeholder="Place where you lost your dog" ng-model="mascota.lugar" /> <br/>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-xs-2 col-xs-offset-3">
                                        <input class="form-control btn-info" type="submit" value="Report" />
                                    </div>
                                    <div class="col-xs-2">
                                        <input class="form-control btn-info" type="reset" value="Cancel" />
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </section>

                <!-- LIST OF MISSING DOGS -->
                <section id="view"  class="row row-content" ng-controller="ListController">
                    <div class="col-xs-offset-3 col-xs-7 well">
                        <div class="col-xs-offset-3 col-xs-9">
                            <h1>View the list of Missing Dogs</h1>
                        </div>
                        <div class="col-xs-offset-2 col-xs-10">
                            <div class="form-group">
                                <label for="race" class="control-label col-xs-11 col-xs-offset-1">Search by race: </label>
                                <div class="col-xs-8 col-xs-offset-1">
                                    <input class="form-control" name="race" type="text" required placeholder="Race of the dogs you are looking for" ng-model="query"/>
                                </div>
                            </div>

                            <div class="col-xs-10">
                                <table class="table table-striped table-responsive" ng-show="mascotas.length > 0 && mascotas != null">
                                    <thead>
                                        <tr>
                                            <th>Name</th>
                                            <th>Race</th>
                                            <th>Description</th>
                                            <th>Place</th>
                                            <th>¿Found?</th>
                                        </tr>
                                    </thead>
                                    <tbody>
        <!-- ACA ESTA EL NG-REPEAT -->  <tr ng-repeat="mascota in mascotas | filter: {raza : query}">
                                            <td>{{ mascota.nombre }}</td>
                                            <td>{{ mascota.raza }}</td>
                                            <td>{{ mascota.descripcion }}</td>
                                            <td>{{ mascota.lugar }}</td>
                                            <td><button
                                                 class="btn btn-block lost"
                                                 ng-class="{found: hover}" 
                                                 ng-mouseenter="hover = true"
                                                 ng-mouseleave="hover = false"
                                                 on-hover="Found"
                                                 on-leave="Lost"
                                                 ng-click="encontrado(mascota.id)"></button></td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </section>

        </div>

        <!-- FOOTER -->
        <footer class="row-footer">
            <div class="container">
                <div class="row">
                    <p class="text-center">&copy Copyrigth 2016 Missing Dog</p>
                </div>
            </div>
        </footer>

        <script src="resources/dependencies/jquery-3.1.1.min.js"></script>
        <script src="resources/dependencies/bootstrap.min.js"></script>
    </body>
</html>

The service ( MascotaService.js ):

(function() {

    var module = angular.module("missingDog");

    var MascotaService = function($resource) {
        return $resource("rest/mascotas/:args", {args: "@args"}, {
            'query': {
                method: 'GET',
                cache: false,
                isArray: true
            }
            });
    };

    module.factory("MascotaService", MascotaService);

}());

And the controller ( FormController.js ):

(function(){

    var module = angular.module("missingDog");

    var FormController = function($scope, MascotaService, $log) {

        $scope.guardar = function() {
            var mascotaJSON = angular.toJson($scope.mascota, true);

            MascotaService.save({args: mascotaJSON});

            $scope.mascota = null; //Vuelve el form al estado del modelo asociado (variable $scope.mascota en este caso)
                                   //Si $scope.mascota es null, el form toma los valores por defecto, 
                                   //de lo contrario toma los valores de la variable

            $scope.mascotas = MascotaService.query(); //Aca refresco la lista después de haber guardado un objeto nuevo.
        };

    };

    module.controller("FormController", FormController);

}());
    
asked by Augusto Herbel 29.09.2016 в 08:58
source

2 answers

1

Your code is fine but the problem is that you send the query before the save method has finished on the server. Something like this should solve your problem.

MascotaService.save({args: mascotaJSON}).$promise.then(function() {
    $scope.mascotas = MascotaService.query(); 
}).catch(function() {
    // maejar error
});

When you use $resource you must use the $promise property to get the promise of the Ajax call associated with the method or you can use the $save method if you have already created the instance. Ex

var instancia = new MascotaService({args: mascotaJSON});
instancia.$save().then(function() {
    $scope.mascotas = MascotaService.query(); 
}).catch(function() {
    // manejar error
});

Usually when you use $resource you do not have to use promises but in your case one call depends on the other so you should expect the first one to end.

    
answered by 29.09.2016 в 19:22
-1

Use it like this:

MascotaService.save({args: mascotaJSON}, function() {
    $scope.mascotas = MascotaService.query(); 
}, function() {
    // captura errores
});

Although I personally use it to create elements with ngResources:

  $scope.mascota = new MascotaService();

  $scope.guardar = function() {

        $scope.mascota.$save({args: mascotaJSON}, function() {
             $scope.mascotas = MascotaService.query(); 
             $scope.mascota = new MascotaService(); //Esto es para limpiar el formulario en caso de que se vuelva a usar y dejarlo listo para realizar otro envió.
        }, function() {
           // captura errores
        });
  };
    
answered by 11.10.2016 в 23:23