2016-02-06 90 views
1

請幫我找到我的編碼問題,我已經完成了所有AngularJS代碼以及用於json編碼的html和php,但無法獲取我的數據數據庫...這裏是我當前的代碼我已經完成了AngularJS代碼,但沒有顯示數據

的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); 
+1

你能告訴我們你得到的錯誤是什麼? –

+0

嗨,就像我在標題中提到的,我的數據沒有顯示出來,當我訪問index.html ... –

回答

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 
}); 
+0

很酷,這是我的問題的解決方案,謝謝@ DerekMT12 –

-1

嘗試綁定您的數據,如

$scope.dataKaryawan = data.data; 

還是儘量讓

$scope.$apply() 

retrive數據後

相關問題