简体   繁体   中英

Using factory to display Data in AngularJS

I want to display data from database to page . i'm using factory service and i see json in firebug .
this is my code :

Html

<div ng-controller="fruitsController">
    <ul>
        <li ng-repeat="fruit in fruits">
            {{fruit.subject}}
        </li>
    </ul>
</div>  

Js

var fruitsApp = angular.module('fruitsApp', [])

fruitsApp.factory('fruitsFactory', function($http) {
    return {
        getFruitsAsync: function(callback) {
            $http.get('insert.php').then(
                function(response){
                    var store = [];
                    store = response.data;
                },
                function(error){
                    console.log(error);
                });

        }
    };
});

fruitsApp.controller('fruitsController', function($scope, fruitsFactory) {
    fruitsFactory.getFruitsAsync(function(results) {
        console.log('fruitsController async returned value');
        $scope.fruits = results.fruits;
    });
});  

this is insert.php

include('config.php');


$data = json_decode(file_get_contents("php://input"));
$subject = mysql_real_escape_string($data->subject);
$body = mysql_real_escape_string($data->body);
mysql_select_db("angular") or die(mysql_error());
mysql_query("INSERT INTO story (subject,body) VALUES ('$subject', '$body')");
Print "Your information has been successfully added to the database.";

$query = "SELECT * FROM story";
$result = mysql_query($query);

$arr = array();
while ($row = mysql_fetch_array($result)) {
    $subject = $row['subject'];
    $body = $row['body'];
    $arr[] = $row;
}
echo json_encode($arr);

json

<b>Notice</b>:  Trying to get property of non-object in <b>D:\xampp\htdocs\Angular\factory\insert.php</b> on line <b>14</b><br />
Your information has been successfully added to the database.[{"0":"","subject":"","1":"","body":""},{"0":"","subject":"","1":"","body":""},{"0":"Soheil","subject":"Soheil","1":"Sadeghbayan","body":"Sadeghbayan"},{"0":"adsas","subject":"adsas","1":"asdasdasda","body":"asdasdasda"},{"0":"Say","subject":"Say","1":"Something","body":"Something"},{"0":"asd","subject":"asd","1":"asdasdasd","body":"asdasdasd"},{"0":"asda","subject":"asda","1":"dasdasd","body":"dasdasd"},{"0":"asd","subject":"asd","1":"asdadd","body":"asdadd"},{"0":"asaS","subject":"asaS","1":"saAS","body":"saAS"},{"0":"adasda","subject":"adasda","1":"dasdasdasdasdasdasd","body":"dasdasdasdasdasdasd"},{"0":"AS","subject":"AS","1":"sASasAS","body":"sASasAS"},{"0":"asd","subject":"asd","1":"asdasd","body":"asdasd"},{"0":"xZ","subject":"xZ","1":"zXzXZX","body":"zXzXZX"},{"0":"weqe","subject":"weqe","1":"qeqeqe","body":"qeqeqe"},{"0":"gf","subject":"gf","1":"kjh","body":"kjh"},{"0":"","subject":"","1":"","body":""},{"0":"","subject":"","1":"","body":""},{"0":"","subject":"","1":"","body":""},{"0":"","subject":"","1":"","body":""}]

what am i missing in this code to display data? thx in advance

I think you need a promise in your controller as well:

fruitsApp.controller('fruitsController', function($scope, fruitsFactory) {
    fruitsFactory.getFruitsAsync().then(
        function(results) {
            console.log('fruitsController async returned value');
            $scope.foo = {};
            $scope.foo.fruits = results;
        }
    );
});

EDIT: Pay attention to the above changes. Also, you will need to change the usage in the html - it is no longer just ˘fruits˘ but foo.fruits instead. Try that. I suppose that you're using ng-repeat to iterate over the items, right?

You're not returning the value from the $http.

IMO, a better way to set this up, since $http returns a promise.

fruitsApp.factory('fruitsFactory', function($http) {
    return {
        getFruitsAsync: function() {
            return $http.get('insert.php');
        }
    };
});

fruitsApp.controller('fruitsController', function($scope, fruitsFactory) {
    fruitsFactory.getFruitsAsync()
      .then(function (response) { // Leveraging the .then from $http promise.
          $scope.fruits = response.data.fruits;
      });
});  

Updated per your JSON addition:

Your JSON doesn't look like valid JSON.

{
    "fruits": [
        {"0":"","subject":"","1":"","body":""},
        {"0":"","subject":"","1":"","body":""},
        {"0":"","subject":"Soheil","1":"Sadeghbayan","body":"Sadeghbayan"}
    ]
}

Would make more sense so that fruit in fruits ends up being each object (model) in your collection of fruits.

This is how I would do it:

var fruitsApp = angular.module('fruitsApp', [])

fruitsApp.factory('fruitsFactory', function($http) {
    return {
        getFruitsAsync: function(callback) { return $http.get('insert.php'); }
    };
});

This way your factory is really returning a promise.

fruitsApp.controller('fruitsController', [ 'fruitsFactory', function($scope, fruitsFactory) {
    fruitsFactory.getFruitsAsync().success( function(results) {
        console.log('fruitsController async returned value');
        $scope.fruits = results.fruits;
    });
}]); 

Then within your controller, you can handle the data response as you see fit. In your case, you're setting a $scope variable to be used in angular's two-way data binding.

try to use $arr [] = array(); in your php file .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM