AngularJs - $ http.get不起作用

时间:2016-10-10 14:21:13

标签: javascript php angularjs angular-ui-bootstrap

无法从PHP文件中获取数据。

PHP

require 'dbconnect.php';

$array_data = array();
$query = "SELECT * FROM user";

$stmt = $conn->prepare($query);
$stmt->execute($array_data);
$result_data = $stmt->fetchAll( PDO::FETCH_ASSOC );

if( !empty($result_data) ) {    

    header('Content-type: application/json');
    $json = json_encode($result_data);
    // echo $json;
    echo preg_replace("/null/", '""', $json); // replace null to ""

}

controller.js

.controller('tableCtrl', function($filter, $sce, ngTableParams, tableService) {

        var data = tableService.data
    //Editable
        this.tableEdit = new ngTableParams({
            page: 1,            // show first page
            count: 10           // count per page
        }, {
            total:data.length, // length of data
            getData: function($defer, params) {
                $defer.resolve(data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
            }
        });
    })

的script.js

.service('tableService', ['$http', function($http){

        this.data = $http.get("data/timesheet.json")

    }])

HTML

<table ng-table="tctrl.tableEdit" class="table table-striped table-vmiddle">
       <tr ng-repeat="w in $data"  ng-class="{ 'active': w.$edit }">
          <td data-title="'ID'">
             <span ng-if="!w.$edit">{{ w.id }}</span>
             <div ng-if="w.$edit"><input class="form-control" type="text" ng-model="w.id" /></div>
          </td>
          ...
       </tr>                        
   </table> 

当我将json数据放入service.js时,例如this.data = [{..}]它正在工作,但现在我只是试图从php文件中提取数据,这是无效的空白的表。谁能帮助我,这里缺少什么?我是AngularJS的新手。

1 个答案:

答案 0 :(得分:0)

试试这个......

.service('tableService', ['$http', function($http){
  this.data = $http.get("yourphpfile.php");
}])

然后

.controller('tableCtrl', function ($filter, $sce, ngTableParams, tableService) {
    this.tableEdit = {};
    tableService.data.then(initNgTable);

    function initNgTable(data) {
        this.tableEdit = new ngTableParams({
                page : 1, // show first page
                count : 10 // count per page
            }, {
                total : data.length, // length of data
                getData : function ($defer, params) {
                    $defer.resolve(data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                }
            });
    }
})

希望这会对你有所帮助!!