2015-06-24 156 views
1

剛剛開始角度。我成功地使用php保存和檢索數據庫中的數據。我也能循環的數據列表項目中,但是當我添加新用戶,當我刷新瀏覽器,它顯示新添加的用戶角度循環不更新

這是我的HTML代碼列表不會只更​​新:

<div> 
    <ul ng-init="get_user()"> 
     <li ng-repeat="user in userInfo ">{{user.user_name}}<a href="" ng-click="prod_delete(product.id)"> --> Delete</a></li> 
    </ul> 
</div> 

這是我的app.js代碼:

var app = angular.module('AddUser', ['ui.bootstrap']); 

app.controller('AppCtrl', function($scope, $http){ 
    $scope.userInfo = []; 

    /** function to add details for a user in mysql referecing php **/ 
    $scope.save_user = function() { 

     $http.post('db.php?action=add_user', 
      { 
       'user_name' : $scope.user_name, 
       'user_email' : $scope.user_email 
      } 
     ) 

     .success(function (data, status, headers, config) { 
      $scope.userInfo.push(data); 
      console.log("The user has been added successfully to the DB"); 
      console.log(data); 
     }) 

     .error(function(data, status, headers, config) { 
      console.log("Failed to add the user to DB"); 
     }); 
    } 

    /** function to get info of user added in mysql referencing php **/ 
    $scope.get_user = function() { 
     $http.get('db.php?action=get_user').success(function(data) 
     { 
      $scope.userInfo = data; 
      console.log("You were succesfull in show user info"); 
      //console.log(data); 
     }) 
    } 

    }); 
+1

應該叫'$ scope.get_user()'方法來再次從數據庫提取數據 –

+1

OP作爲parkar說,這應作爲NG-INIT只調用一次。 – squiroid

+0

但GY22正在將'data'推入'userInfo'成功$ http.post –

回答

1

當你正在做數據保存數據庫通過服務器的方法,但在你成功的郵政通話你推動的數據在userInfo對象,技術上聽起來不對。

我更喜歡在post調用成功後使用ajax從db獲取新數據,使用$scope.get_user()

代碼

$scope.save_user = function() { 
    $http.post('db.php?action=add_user', { 
     'user_name' : $scope.user_name, 
     'user_email' : $scope.user_email 
    }).success(function (data, status, headers, config) { 
     //$scope.userInfo.push(data); //remove this line 
     $scope.get_user(); //this will fetch latest record from DB 
     console.log("The user has been added successfully to the DB"); 
     console.log(data); 
    }).error(function(data, status, headers, config) { 
     console.log("Failed to add the user to DB"); 
    }); 
} 
0

嘗試更改保存用戶的:

$scope.save_user = function() { 
    $http.post('db.php?action=add_user', { 
     'user_name' : $scope.user_name, 
     'user_email' : $scope.user_email 
    }) 
    .success(function (data, status, headers, config) { 
     $scope.userInfo.push(data.data); 
     console.log("The user has been added successfully to the DB"); 
     console.log(data); 
    }) 
    .error(function(data, status, headers, config) { 
     console.log("Failed to add the user to DB"); 
    }); 
} 

我認爲你正在返回的數據是一個對象,無論你期望的數據是data.data,所以你推送一個無效的對象到你的userInfo數組中

+0

我建議推送來自http響應的添加的用戶名和電子郵件,以確保東西添加正確,以防萬一你有一些參數名稱錯字,實際上保存在一些領域的空白。 – Icycool

+0

已更新,我認爲問題是數據在data.data下返回,因此循環所尋找的鍵不存在於他正在推送的對象上 –