Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to get json data from a php file to use within an Angular controller. Im echoing json_encode(pg_fetch_assoc($result)); within the php file and when I console.log($scope.contents); in the angular controller it brings back the json data, but it comes back empty when I try doing an ng-repeat

controllers.js:

myApp.controller('ContentCtrl', function ($scope, $http) {
  $http({method: 'GET', url: 'content.php'}).success(function(data) {
    $scope.contents = data;
  });
});

content.php:

<?php
require_once("sdb.php");
$result = pg_query($dbconn, "SELECT * FROM content ORDER BY name ASC");
echo json_encode(pg_fetch_assoc($result));

index.php:

<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/style.css"/>
</head>
<body ng-app="myApp">
 <div ng-controller="ContentCtrl">
   <ul>
     <li ng-repeat="content in contents">
       <a href="#">{{content.name}}</a>
     </li>
   </ul>
 </div>
</body>
   <script src="js/jquery-1.10.2.js"></script>
   <script src="js/angular.min.js"></script>
   <script src="js/controllers.js"></script>
</html>
share|improve this question

1 Answer 1

up vote 2 down vote accepted

You'll want to actually send the data as JSON. To do that, you just need to add header('Content-Type: application/json'); before your echo statement. So content.php becomes:

<?php
require_once("sdb.php");

$result = pg_query($dbconn, "SELECT * FROM content ORDER BY name ASC");

header('Content-Type: application/json');
echo json_encode(pg_fetch_assoc($result));

As an aside, there are a few things you may want to do with your controller. I would change this:

myApp.controller('ContentCtrl', function ($scope, $http) {
    $http({method: 'GET', url: 'content.php'}).success(function(data) {
        $scope.contents = data;
    });
});

to this:

myApp.controller('ContentCtrl', ['$scope', '$http', function ($scope, $http) {
    $http.get('content.php')
    .success(function(data) {
        $scope.contents = data;
    });
}]);

The additional '$scope', '$http', before the function definition allows you to minify in the future, and the .get is just personal preference, but I think it's cleaner to read.

share|improve this answer
    
Thanks for the fast answer! –  MichaelWilson2013 Jul 31 at 17:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.