Peter
Peter

Reputation: 2404

Cant make $http work, not showing response

I can´t make $http work and also, I can´t find WHAT is the problem. The "request" is working (200) but I do not know WHY I can´t show the results. I´m really stuck.

Here is the code.

index.html

<div ng-app="app1" ng-controller="mcontrol as ctrl">
<div ng-repeat="x in ctrl.list">
<span ng-bind="x.name"></span>
</div>
</div>

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

<script>
angular.module("app1", [])
.controller("mcontrol", ["$http", function($http)
{
    $http.get("myfile.php").then(function(response)
    {
        this.list = response.data;
    },
    function(errorresponse)
    {
        console.error("Error");
    });
}]);

</script>

myfile.php

[
{name: "Juan"},
{name: "Carlos"},
{name: "Ramiro"}
]

Console

GET 
http://127.0.0.1:5000/index.html [HTTP/1.1 200 OK 31ms]
GET 
http://127.0.0.1:5000/angular.js [HTTP/1.1 304 Not Modified 12ms]
GET 
XHR 
http://127.0.0.1:5000/myfile.php [HTTP/1.1 304 Not Modified 14ms]

Anyone can help me? Thanks!

Upvotes: 1

Views: 37

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136174

Its kind of context scoping related issue, this you are using inside $http is not the this of the controller function.

I'd say that create a variable & assign this into it, inside your controller function itself like var vm = this.

Code

angular.module("app1", [])
.controller("mcontrol", ["$http", function($http) {
    var vm = this;
    $http.get("myfile.php")
     .then(function(response) {
        vm.list = response.data;
     },
     function(errorresponse) {
        console.error("Error");
    });
}]);

Upvotes: 1

Related Questions