我已完成AngularJS代码但数据未显示

时间:2016-02-06 16:22:47

标签: javascript php angularjs json

请帮我找到我的编码问题,我已经完成了所有AngularJS代码和html和php的json编码,但我无法获取数据库中的数据...这是我当前的代码

的index.html

 <body ng-app="myApp" ng-controller="KaryawanCtrl">

<form method="post">
  <input type="text" ng-model="karyawan.nama">
  <input type="text" ng-model="karyawan.alamat">
  <input type="submit" ng-click="tambahData()" value="simpan">
</form>
<table ng-init="dapatkanData()">
    <thead>
    <th>nama</th>
    <th>alamat</th>
    </thead>
    <tr ng-repeat="item in dataKaryawan">
        <td>{{item.nama}}</td>
        <td>{{item.alamat}}</td>
    </tr>
</table>

这是角度代码

JS / app.js

 var app= angular.module("myApp",[]);
  app.controller("KaryawanCtrl",function($scope,$http){
    //variabel awal
    $scope.aksi="tambah";
    $scope.karyawan={};
    //angularjs untuk menyimpan data ke database
    $scope.tambahData = function(){
        $http.post(
          'post.php',
          {
            data: $scope.karyawan
          }
        ).success(function(data){
          alert("data berhasil dimasukkan");
        }).error(function(){
          alert("Gagal menyimpan data");
        });

        //angularJS untuk menampilkan data ke tabel
        $scope.dapatkanData = function(){
          $http.get('karyawan.php').success(function(data){
              $scope.dataKaryawan = data;
          });  
        };

        };
    });

这是php

$koneksi = mysqli_connect("localhost","root","","belajar") or die("tidak bisa tersambung ke database");
$perintah_sql = "SELECT * FROM karyawan";

$data = [];
$result = mysqli_query($koneksi,$perintah_sql);

while($row= mysqli_fetch_array($result)){
  $temp_data = [];
  $temp_data['nama']= $row['nama'];
  $temp_data['alamat']=$row['alamat'];
  array_push($data,$temp_data);
}

echo json_encode($data);

2 个答案:

答案 0 :(得分:1)

问题是您的dapatkanData函数是在tambahData函数内定义的。只需将它移到外面就可以了,它应该可以工作:

var app= angular.module("myApp",[]);

app.controller("KaryawanCtrl",function($scope,$http){
   //variabel awal
   $scope.aksi="tambah";
   $scope.karyawan={};

   $scope.tambahData = function(){
       $http.post('post.php',{ data: $scope.karyawan }).success(function(data){
         alert("data berhasil dimasukkan");
       }).error(function(){
         alert("Gagal menyimpan data");
       });
    };

    $scope.dapatkanData = function(){
      $http.get('karyawan.php').success(function(data){
          $scope.dataKaryawan = data;
      });  
    };

    $scope.dapatkanData(); // Use this instead of ng-init. Remove that from the html
});

答案 1 :(得分:-1)

尝试绑定您的数据,如

$scope.dataKaryawan = data.data;

或尝试制作

$scope.$apply()

经过反复数据