FranP FranP - 1 month ago 11
JSON Question

ng-repeat gets commented and doesn´t show results from a JSON object

I have this code, and I don´t know why, but ng-repeat Directive gets commented and doesn´t show the results of the JSON object. I have checked if the object is properly passed to "this.paises2 with the toSource() method and it seems everything is fine.

I have checked here, but nothing works:

AngularJS: ng-repeat not displaying JSON

ng-repeat code getting commented out when viewed from browser

ngRepeat div get commented out when i see from the browser inspector

Here is the HTML code:

<html ng-app="miModulo">



<head>

<link href="mis-css.css" rel="stylesheet" type="text/css">

</head>

<body ng-controller="miControlador as vm">

<button ng-click="vm.buscarEnRegion()">Pulsar</button>



<ul ng-repeat="elemento in vm.paises">
<li>

{{elemento.name}}



</li>

</ul>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<script src="mijs1.js"></script>

</body>




And the Javascript/ Angular JS code:

angular
.module("miModulo",[])
.controller("miControlador",['$http',funcionPrincipal] );

function funcionPrincipal($http)
{
this.buscarEnRegion=function()
{
$http.get("https://restcountries.eu/rest/v1/region/africa").then(function(miRespuesta)
{
this.paises=miRespuesta;

// alert(miRespuesta.toSource());

alert(this.paises.toSource());



},function(miRespuesta)
{

alert("incorrecto");
}



); //then


}


}


Thanks in advance.

Answer Source

A couple issues. From the angular docs

The response object has these properties:

  • data – {string|Object} – The response body transformed with the
  • transform functions. status – {number} – HTTP status code of the
  • response. headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate
  • the request. statusText – {string} – HTTP status text of the response.
  • xhrStatus – {string} – Status of the XMLHttpRequest (complete, error, timeout or abort).

So what you want is miRespuesta.data.

The other issue is when you do this.paises=miRespuesta, this refers to the the function, not the controller. So you need to assign a variable to the controller. So change your controller to this:

function funcionPrincipal($http)
{   
    var vm = this;
    vm.buscarEnRegion=function()
    {
        $http.get("https://restcountries.eu/rest/v1/region/africa").then(function(miRespuesta) 
        {
            vm.paises=miRespuesta.data;
        },function(miRespuesta)
        {
            alert("incorrecto");
        }
        ); //then
    }
}

See plunker