2012-08-31 115 views
0

我想實現刪除使用PHP angularjs功能如下: 刪除: index.html的觀點:angularjs刪除通過PHP

<ul> 
      <li ng-repeat="r in result"> 
      {{r.description}}|{{r.name}} | <a href='' ng-click = "edit(r.product_id)">edit</a> | <a href='' ng-click = "delete(r.product_id)">delete</a> 
      <input type="hidden" name="hdnid" ng-model="hdn" value="{{r.product_id}}"/> 
      </li> 
     </ul> 

在控制器: 刪除:

//delete 
     $scope.delete = function() { 
      var elem = angular.element($element); 
      var dt = $(elem).serialize(); 
      //alert($element); 
      console.log($(elem).serialize()); 
      $http({ 
       method: 'POST', 
       url: 'php/delete.php', 
       data: dt, 
       headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
      }).success(function(data, status) { 
       $scope.status = status; 
       $scope.data = data; 
       $scope.rs = data; // Show result from server in our <pre></pre> element 
      }).error(function(data, status) { 
       $scope.data = data || "Request failed"; 
       $scope.status = status; 
      }); 
     }; 

並在php文件中:delete.php

<?php 
include 'connect.php'; 
mysql_select_db($database,$con); 
$id = $_POST['hdnid']; 
$query = "delete from `product` where `product_id` = $id"; 
$result = mysql_query($query) OR die(mysql_error()); 
echo "You have successfully deleted "; 
?> 

記錄被刪除,但頁面未刷新。我無法看到記錄被刪除,直到我刷新頁面。 我哪裏錯了?如何刷新頁面?

+0

我很困惑捕捉它的工作:你爲什麼把AJAX操作的結果'$ scope.rs'和'$ scope.data',但是不要以任何方式更改'$ scope.result'? – raina77ow

+0

我是一個完整的noob angularjs所以我不知道這個。我應該如何更改$ scope.result?實際上結果是什麼? – z22

+0

http://tech-blog.maddyzone.com/javascript/perform-addeditdeleteview-php-using-angular-js希望它會有幫助 –

回答

2

您需要將其從您的範圍中刪除才顯示出來。我們不需要元素ID傳遞到範圍得到它,當我們點擊我們可以用this關鍵字

$scope.delete = function() { 
     //Store the this variable so we can use it in the $http functions 
     var that = this 
     var elem = angular.element($element); 
     var dt = $(elem).serialize(); 
     //alert($element); 
     console.log($(elem).serialize()); 
     $http({ 
      method: 'POST', 
      url: 'php/delete.php', 
      data: dt, 
      headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
     }).success(function(data, status) { 
      // get the elements index and then remove it from the results array 

      $scope.result.splice(that.$index, 1); 
      $scope.status = status; 
      $scope.data = data; 
      $scope.rs = data; // Show result from server in our <pre></pre> element 
     }).error(function(data, status) { 
      $scope.data = data || "Request failed"; 
      $scope.status = status; 
     }); 
    }; 
+0

我試過了,但仍然一樣。 btw什麼是美元指數?它是由angularjs提供的嗎?我試圖作爲$ scope.products.splice(即。$ index,1);然後$ scope.products = data; – z22

+0

當你使用'ng-repeat'的時候,它爲它通過'$ index'屬性訪問的每個項目創建一個數組索引。 – powerc9000

+0

我試過了,還沒有工作。該頁面不刷新。 – z22