1

Hi everyone I'm learning angular i wrote a simple app but i don't know how i can update the model or the view ,later of get http json.

angular.module("dataApp",[])

.controller("ctrlData",function($scope,$http){
    $http.get('consulta.php')
    .success(function(data){
        //console.log(data);
        $scope.personas = data;
    }).error(function(error){
        console.log(error);
    }); });//end ctrl

output of consulta.php

[
    {
        "id_persona":"1",
        "nombre":"sebastian",
        "apellido":"rincon ",
        "telefono":"4422404",
        "direccion":"calle 93 # 23 2132"
    },
    {
        "id_persona":"2",
        "nombre":"leiton",
        "apellido":"aricapa",
        "telefono":"4421112313",
        "direccion":"calle 634 supia avenia 93"
    },
    {
        "id_persona":"3",
        "nombre":"daniel",
        "apellido":"desconocido",
        "telefono":"645452423",
        "direccion":"urbanizacion los vientos 123"
    },
    {
        "id_persona":"4",
        "nombre":"angularjs",
        "apellido":"javascript",
        "telefono":"0231391",
        "direccion":"module controller 321"
    },
    {
        "id_persona":"5",
        "nombre":"mark",
        "apellido":"zuckerberg",
        "telefono":"423423423",
        "direccion":"palo alto california"
    }
]

index.html

<tr ng-repeat="persona in personas">

            <td>{{persona.id_persona}}</td>
            <td>{{persona.nombre}}</td>
            <td>{{persona.apellido}}</td>
            <td>{{persona.telefono}}</td>
            <td>{{persona.direccion}}</td>
</tr>

Everything works well but if I insert a new row in the database mysql angularjs will dont know it, i need refresh the page for view the new row. For other hand i tried setTimeout function

setTimeout(function(){

    $http.get('consulta.php')
    .success(function(data){
        console.log(data);
        $scope.personas = data;
    }).error(function(error){
        console.log(error);
    });

},1000);

but i think that is not is the correct!. please help thanks.

cst1992
  • 3,823
  • 1
  • 29
  • 40
zebaz
  • 13
  • 3
  • 1
    Don't use `.success()` and `.error()`. Those are old and depending on your version of AngularJS, may not even work. Rather, use `.then()`. – cst1992 Jul 03 '17 at 18:00
  • how are you inserting a row in your database ? show us that code. Or did you mean to insert a row using sql outside of your app ? – Gonzalo.- Jul 03 '17 at 18:10

2 Answers2

0

You'll need to call the service again for the view to update.

When you write the $http.get() call in the controller, it's called only once when the view loads. After that it's not called.

You could use something like setInterval which periodically calls your service.

angular.module("dataApp",[])
.controller("ctrlData",function($scope,$http){
    setInterval(function(){
        $http.get(...)
    }, 60000);
});

That'll call your service every minute to update your view.

Note, though, that you shouldn't be using $http directly in your controller; rather use a service.

cst1992
  • 3,823
  • 1
  • 29
  • 40
0

If you want your web application to react to server-side changes you'll either need something like web sockets or similar, or poll the API regularly. I reckon the first (best) options might be a bit too complex for you at this point, so that leaves the second.

Before you start implementing something like this, you'll have to be certain you actually need your view to react to changes without user interaction. Why isn't it enough to just wait for the user to either refresh (or change route)?

Anyways, here's one way you could create a service to poll your API for data:

angular.module('dataApp').service('personaService', PersonaService);

function PersonaService($http, $q, $interval){  
    var pollingInterval;

    this.getConsulta = getConsulta;
    this.startGetConsulta = startGetConsulta;
    this.stopGetConsulta = stopGetConsulta;

    function startGetConsulta(interval){
        if(pollingInterval){
            return $q.resolve();
        }
        var deferred = $q.defer();

        // Get first time
        getConsulta().then(function(data){
            deferred.notify(data);
        }, function(response){
            deferred.reject(response);
        });
        // Start polling
        pollingInterval = $interval(function(){
            getConsulta().then(function(data){
                deferred.notify(data);
            }, function(response){
                deferred.reject(response);
            });
        }, interval);

        return deferred.promise;
    }

    function stopGetConsulta(){
        if(angular.isDefined(pollingInterval)) {
            $interval.cancel(pollingInterval);
        }
        pollingInterval = null;
    }

    function getConsulta(){
        return $http.get('consulta.php')
            .then(function(response){ return response.data; } );
    }
}

To use it, you'll inject in into your controller and start polling like this:

angular.module("dataApp",[])
.controller("ctrlData",function($scope, personaService){

    personaService.startGetConsulta(60000).then(null, null, function(data){
        $scope.personas = data;
    });

});

Note that since we're using notify instead of resolve, for the promise returned by the service, we're using the third notify-callback when consuming the promise in the .then(..) function.

That should do it. But just to cement things - don't just use this blindly. First make sure you actually need your view to be this reactive. Then make sure you actually understand what is going on in the above sample.

Here's a plunker showing this in action

Nikolaj Dam Larsen
  • 5,455
  • 4
  • 32
  • 45