无法使用angular.js和PHP绑定视图上的数据

时间:2015-09-25 09:16:39

标签: php mysql angularjs

我需要使用Angular.js在页面上显示数据。首先,我使用PHP从数据库中获取所有数据。这里没有数据显示在页面上。我在浏览器控制台中获取了以下检索到的数据。

 public String execute(HttpServletRequest request){
       Runnable r = new RunnableImplementation(request);
       Thread t = new Thread(r);
       t.start();
       return "Success";
    }

我正在解释下面的代码。

  

read.js:

all data [{"0":"1","id":"1","1":"","name":"","2":"","pass":"","3":"","email":""},{"0":"2","id":"2","1":"subhra","name":"subhra","2":"12345","pass":"12345","3":"subh@gmail.com","email":"subh@gmail.com"},{"0":"3","id":"3","1":"rakesh","name":"rakesh","2":"0901209474","pass":"0901209474","3":"maini","email":"maini"},{"0":"4","id":"4","1":"raj","name":"raj","2":"23457","pass":"23457","3":"rai","email":"rai"},{"0":"5","id":"5","1":"Rahul","name":"Rahul","2":"098765","pass":"098765","3":"shinha","email":"shinha"}]  
  

read.php:

var app=angular.module('Read_data',[]);
app.controller('readController',function($scope){
    $.ajax({
        type:'GET',
        url:"php/read.php",
        success: function(data){
            $scope.data=data;
            console.log('all data',$scope.data);
        }
    })
});
  

的index.html:

<?php
//database settings
$connect = mysqli_connect("localhost", "root", "*******", "AngularTest");
$result = mysqli_query($connect, "select * from users");
$data = array();
while ($row = mysqli_fetch_array($result)) {
  $data[] = $row;
}
    print json_encode($data);
?>

请帮我解决此问题,并成功绑定表格中的所有数据。

1 个答案:

答案 0 :(得分:2)

Angular不知道更新的数据。如果您没有使用$http进行AJAX,请使用$scope.$apply

var app=angular.module('Read_data',[]);
app.controller('readController',function($scope){
    $.ajax({
        type:'GET',
        url:"php/read.php",
        success: function(data){
            $scope.$apply(function(){
                $scope.data = angular.fromJson(data);
            });
            console.log('all data',$scope.data);
        }
    })
});

或使用$http(推荐)

var app=angular.module('Read_data',[]);
app.controller('readController',function($scope, $http){
    $http.get('php/read.php').
        then(function(data) {
            // this callback will be called asynchronously
            // when the response is available
            $scope.data = data.data;
        }, function(response) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
        });
});