View is loaded before the data in the controller

0

I'm new to Ionic, and I'm doing an app that from a button, calls a function in a controller. The function makes http and brings data with php to make a list in another view. But ... the view is loaded and the data is not yet available. (The PHP works correctly) In addition, I have variable logic, which indicates when the view is loaded that even the data is not. I will appreciate if you help me solve this ... asynchronism? Thank you very much!

 var request = $http({
        method: "post",
            url: "http://............php",
            data: {
                ciudad: $scope.ciuid,
            },
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        });
        /* Successful HTTP post request or not */
        request.success(function (data) {

        $scope.arrs = [];
        for (var prop in data) {
            $scope.arrs.push(data[prop]);
        }    
        $scope.AtraccLoaded = true;
        alert($scope.arrs[0].aarqu); // muestra dato, correcto !

View ----------------------------------

<a ng-repeat="arr in arrs" ng-if="AtraccLoaded" 
               href="#/{{arr.anomb}}"
               class="item item-thumbnail-left">
              <img ng-src="{{ arr.imag }}">
              <h2>{{ arr.anomb }}</h2>
              <h4>{{ arr.adire }}</h4>
    </a>
    
asked by Guillermo Rodriguez 27.01.2017 в 20:17
source

2 answers

1

Loading the view before the data is not a problem in angularjs (and less using ionic), since one of the most outstanding features of this library is the 2-Way-data-binding, which makes sure it is checking all the time the model with the view.

Since you're using ionic, try using the ionic list tags:

<ion-list>
  <ion-item ng-repeat="item in items">
    Hello, {{item}}!
  </ion-item>
</ion-list>

link

Also I do not think you should use the href on your tag.

    
answered by 01.02.2017 в 17:06
0

It's because you're making an asynchronous call. Remember that using $ http means waiting for the server for an answer and this takes time until you get an answer, so you must handle it with a promise ($ q angularjs promise).

Important: Do not mix your MVC model in the controller, there should only be consumption of api points. And your definitions must be separated.

Example of api consumption:

angular.module('ciudades', []).service('Ciudades', ['$q','$http', function($q, $http) {
    var self = {

        listaCiudades: function(_ciudad) {
            var deferred = $q.defer();//esta es la promesa que luego se va a resolver

            var url = "http://.....php";
            var data = {ciudad: _ciudad};

            $http.post(url, data).then(function(response) {
                deferred.resolve(response.data);//response son los datos que retorna tu php

            }, function(error) {
                deferred.reject(error);//si algo va mal igualmente se maneja
            });

            return deferred.promise;
        }

    };

    return self;
}]);

Later you must inject it into your app.js (by default in ionic) where is the main module

var app = angular.module('nombreDeTuApp', ['ionic', 'ciudades'])
//aca va con el nombre con el cual registrate el modulo anterior que en este ejemplo usamos ciudades en minúsculas

Then we will consume it in the driver we need.

app.controller('Controller', function ($scope, Ciudades) {
//aca puedes ver que estamos usando el nombre ciudades en mayúscula y de esta forma lo vamos a consumir
//por ejemplo supongamos que cargamos los datos de la ciudad 'ABC' pues no se que retorna tu php

$scope.ciudad = {};

$scope.$on('$ionicView.enter', function () {
    Ciudades.listaCiudades('ABC').then(function(ciudad){
    $scope.ciudad = ciudad;//por tanto en este instante ya se termino la llamada http y estas consumiendo los datos que retorna la promesa($q)
    //recuerda que esto puede tomar un tiempo por lo cual es aconsejable mostrar algún loading hasta que obtengas respuesta
    //y tu vista ya será actualizada
    }, function(error){
    //algo fue mal con la llamada te retorna el error
    });
});


});
    
answered by 21.02.2017 в 17:27