2017-02-23 172 views
0

У меня есть код с кодом пользователя с использованием угловых js и php ... у него есть столбец статуса, из которого можно обновить статус пользователя. Статус обновляется в базе данных должным образом, но кнопка изменяется только после перезагрузки страницы ... как ее можно изменить после успешного ответа без перенаправления страниц?обновить модальные данные о статусном обновлении в угловых js с php

Ниже приведен код JS файл:

var app = angular.module("crudApp",[]); //define application 
/* 
* $scope : javascript object that joins controller with view 
* Model data is accesed via $scope variable 
* $http : function taht allows communication with remote servers 
*/ 
app.controller("userController",function($scope,$http){ 
    $scope.users =[]; //defining model for "userController" controller 
    $scope.tempUserData ={}; 
    $scope.getRecords = function(){ //define function to fetch all users 
     $http.get('action.php',{ 
      params:{ 
       'type':'view' 
      } 
     }).success(function(response){ 
      if(response.status == 'OK'){ 
       $scope.users = response.records; 
      } 
     }) 
    }; 
    $scope.saveUser = function(type){ 
     var data = $.param({ 
      'data':$scope.tempUserData, 
      'type':type 
     }); 
     var config = { 
      headers : { 
       'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' 
      } 
     }; 
     $http.post("action.php", data, config).success(function(response){ 
      if(response.status == 'OK'){ 
       if(type == 'edit'){ 

       }else{ 
        $scope.users.push({ 
         id:response.data.id, 
         name:response.data.name, 
         email:response.data.email, 
         phone:response.data.phone, 
         created:response.data.created 
        }); 

       } 
       $scope.userForm.$setPristine(); 
       $scope.tempUserData = {}; 
       $('.formData').slideUp(); 
       $scope.messageSuccess(response.msg); 
      }else{ 
       $scope.messageError(response.msg); 
      } 
     }); 
    }; 
    // function to add user 
    $scope.addUser = function(){ 
     $scope.saveUser('add'); 
    }; 

    // function to delete user 
    $scope.deleteUser = function(user){ 
     var conf = confirm("Are you sure to delete user?"); 
     if(conf == true){ 
      var data = $.param({ 
       'id': user.id, 
       'type': 'delete' 
      }); 
      var config = { 
       headers: { 
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' 
       } 
      }; 
      $http.post('action.php', data, config).success(function(response){ 
       if(response.status == 'OK'){ 
        var index = $scope.users.indexOf(user); 
        $scope.users.splice(index,1); 
        $scope.messageSuccess(response.msg); 
       }else{ 
        $scope.messageError(response.msg); 
       } 
      }); 
     } 
    }; 

    //funtion to maintain user status 
    $scope.changeStatus = function(user,status){ 

     var conf = confirm("Are you sure to update user status?"); 
     if(conf == true){ 
      var data = $.param({ 
       'id': user.id, 
       'type': 'updateStatus', 
       'status': status 
      }); 
      var config = { 
       headers: { 
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' 
       } 
      }; 
      //console.log(data); 
      $http.post('action.php', data, config).success(function(response){ 
       if(response.status == 'OK'){ 
        $scope.messageSuccess(response.msg); 
       }else{ 
       } 
      }); 
     } 
    } ; 
    // function to display success message 
    $scope.messageSuccess = function(msg){ 
     $('.alert-success > p').html(msg); 
     $('.alert-success').show(); 
     $('.alert-success').delay(5000).slideUp(function(){ 
      $('.alert-success > p').html(''); 
     }); 
    }; 

    // function to display error message 
    $scope.messageError = function(msg){ 
     $('.alert-danger > p').html(msg); 
     $('.alert-danger').show(); 
     $('.alert-danger').delay(5000).slideUp(function(){ 
      $('.alert-danger > p').html(''); 
     }); 
    }; 
}) 

Index.html, как показано ниже:

<!DOCTYPE html> 
<html> 
<head> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> 
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> 
    <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script> 
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"> 
    <script src="script.js"></script> 
    <style> 
    /* required style*/ 
    .none{display: none;} 

    /* optional styles */ 
    table tr th, table tr td{font-size: 1.2rem;} 
    .row{ margin:20px 20px 20px 20px;width: 100%;} 
    .glyphicon{font-size: 20px;} 
    .glyphicon-plus{float: right;} 
    a.glyphicon{text-decoration: none;cursor: pointer;} 
    .glyphicon-trash{margin-left: 10px;} 
    .alert{ 
     width: 50%; 
     border-radius: 0; 
     margin-top: 10px; 
     margin-left: 10px; 
    } 

    </style> 
</head> 

<body ng-app="crudApp"> 
<div class="container" ng-controller="userController" ng-init="getRecords()"> 
    <div class="row"> 
     <div class="panel panel-default users-content"> 
      <div class="panel-heading">Users 
       <a href="javascript:void(0);" class="glyphicon glyphicon-plus" onclick="$('.formData').slideToggle();"></a> 
      </div> 
      <div class="alert alert-danger none"><p></p></div> 
      <div class="alert alert-success none"><p></p></div> 
      <div class="panel-body none formData"> 
       <form class="form" name="userForm"> 
        <div class="form-group"> 
         <label>Name</label> 
         <input type="text" class="form-control" name="name" ng-model="tempUserData.name"/> 
        </div> 
        <div class="form-group"> 
         <label>Email</label> 
         <input type="text" class="form-control" name="email" ng-model="tempUserData.email"/> 
        </div> 
        <div class="form-group"> 
         <label>Phone</label> 
         <input type="text" class="form-control" name="phone" ng-model="tempUserData.phone"/> 
        </div> 
        <a href="javascript:void(0);" class="btn btn-warning" onclick="$('.formData').slideUp();">Cancel</a> 
        <a href="javascript:void(0);" class="btn btn-success" ng-hide="tempUserData.id" ng-click="addUser()">Add User</a> 
        <a href="javascript:void(0);" class="btn btn-success" ng-hide="!tempUserData.id" ng-click="updateUser()">Update User</a> 
       </form> 
      </div> 

      <table class="table table-striped"> 
       <tr> 
        <th width="5%">#</th> 
        <th width="20%">Name</th> 
        <th width="30%">Email</th> 
        <th width="20%">Phone</th> 
        <th width="14%">Created</th> 
        <th width="0%">Status</th> 
        <th width="10%">Action</th> 
       </tr> 
       <tr ng-repeat="user in users"> 
        <td>{{ $index + 1 }}</td> 
        <td>{{ user.name }}</td> 
        <td>{{ user.email }}</td> 
        <td>{{ user.phone }}</td> 
        <td>{{ user.created }}</td> 
        <td ng-if="user.status == 1"><button class="button" ng-class="{'active': isActive}" ng-click="changeStatus(user,0)" type="button">Active</button></td> 
        <td ng-if="user.status == 0"><button class="button" ng-class="{'active': isActive}" ng-click="changeStatus(user,1)" type="button">Inactive</button></td> 
        <td> 
         <a href="javascript:void(0);" class="glyphicon glyphicon-edit" ng-click="editUser(user)"></a> 
         <a href="javascript:void(0);" class="glyphicon glyphicon-trash" ng-click="deleteUser(user)"></a> 
        </td> 
       </tr> 
      </table> 
     </div> 
    </div> 
</div> 
</body> 

</html> 

ответ

0

Это потому, что вы не обновляя статус user объекта.

Измените функцию ng-click и добавьте $index, чтобы вы могли отслеживать соответствующего пользователя и обновлять статус.

<td ng-if="user.status == 1"><button class="button" 
     ng-class="{'active': isActive}" ng-click="changeStatus($index, user,0)" 
     type="button">Active</button></td> 
<td ng-if="user.status == 0"><button class="button" 
     ng-class="{'active': isActive}" ng-click="changeStatus($index, user,1)" 
     type="button">Inactive</button></td> 

Измените changeStatus метод подписи, как показано ниже:

// Funtion сохранить статус пользователя $ scope.changeStatus = функция (userIndex, пользователь, статус) {

var conf = confirm("Are you sure to update user status?"); 
    if(conf == true){ 
     var data = $.param({ 
      'id': user.id, 
      'type': 'updateStatus', 
      'status': status 
     }); 
     var config = { 
      headers: { 
       'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' 
      } 
     }; 
     //console.log(data); 
     $http.post('action.php', data, config).success(function(response){ 
      if(response.status == 'OK'){ 
       // update the `user` Array 
       $scope.users[userIndex].status = status; 
       $scope.messageSuccess(response.msg); 
      }else{ 
      } 
     }); 
    } 
} ; 

Я реализовал аналогичный вид поведения без использования бэкэнда. Посмотри мои plnkr

+0

Спасибо, это сработало для меня .. –

Смежные вопросы