Как мне отправить мою угловую форму?

#mysql #angularjs #codeigniter

#mysql #angularjs #codeigniter

Вопрос:

У меня есть страница редактирования, и я хотел бы отправить информацию в БД после редактирования полей, это кажется чем-то простым, но я не могу найти хороший пример, который относится к моей ситуации, я действительно не знаю, как это решить, это последняя часть моего проекта. Я был бы признателен за любые предложения, пожалуйста.

Это мой код страницы редактирования:

   <title>

  </title>
</head>
<body ng-app="app" ng-controller="decontroller" class="container">

<div id="banner" style="text-align:center; margin-left:auto; margin- right:auto; display:block;">



 </div>


<h2></h2>
<h3>Personal Information:</h3>
<div id="validation-errors">
</div>

<form action="" method="post" accept-charset="utf-8" ng-submit="addEdit()">
<table class="table table-bordered">
 <tbody>
  <tr>
  <td>ParticipantID</td>
  <td>{{edit.Stlc_id}}</td>
</tr>
<tr>
  <td>First Name:<br>
  </td>
  <td>{{edit.First_Name}}</td>
</tr>
<tr>
  <td>Last Name:<br>
  </td>
  <td>{{edit.Last_Name}}</td>
</tr>
<tr>
  <td>Address:</td>
  <td><input type="text" name ="Address" ng-model="edit.Address" ></td>
</tr>
<tr>
  <td>Phone:</td>
  <td><input size="20" name ="phone" ng-model="edit.Phone_Number" ></td>
</tr>
<tr>
  <td>Assistive Devices:</td>
  <td><input name ="AssistiveDevices" ng-model="edit.Assistive_Devices" ></td>
</tr>
<tr>
  <td>Lanyard Code</td>
  <td>
    <input name ="Lanyard_Status" ng-model="edit.Lanyard_Status"  /> </td>
</tr>
<tr>
  <td>Comments</td>
  <td>
    <textarea cols="100" name="comments" ng-model="edit.Comments">.</textarea>
    </td>
</tr>
<tr>
  <td>Disenrolled</td>
  <td><input name="disenrolled" ng-model="edit.Disenrolled" ></td>
</tr>
<tr>
  <td>Deceased</td>
  <td><input name="deceased" ng-model="edit.Deceased" ></td>
</tr>
</tbody>
</table>
</form>

<h3>Days in Center<br></h3>
<table class="table table-bordered">
<tbody>
 <tr>
  <td>Monday</td>
  <td>Tuesday</td>
  <td>Wednesday</td>
  <td>Thursday</td>
  <td>Friday</td>
</tr>
<tr>
  <td><input name="Attendance_Monday" ng-model="edit.Attendance_Monday" ></td>
  <td><input name="Attendance_Tuesday"  ng-model="edit.Attendance_Tuesday" ></td>
  <td><input name="Attendance_Wednesday" ng-model="edit.Attendance_Wednesday" ></td>
  <td><input name="Attendance_Thursday"  ng-model="edit.Attendance_Thursday" ></td>
  <td><input name="Attendance_Friday"  ng-model="edit.Attendance_Friday" > </td>
</tr>
</tbody>
</table>

<h3>Transportation Types</h3>
<table class="table table-bordered">
<tr>
 <td>Type of Transportation</td>
<td>Approved For</td>
<td>Comments</td>
</tr>
<tr>
<td width="300px">Wheel Chair Van</td>
<td><input name="WheelChair_Van" ng-model="edit.WheelChair_Van"></td>
<td><textarea cols="100" name="WheelChair_Van comments" ng-model="edit.Comments" ></textarea></td>
</tr>
<tr>
<td width="300px">Transit Van 240</td>
<td><input name="TransitVan_240" ng-model="edit.TransitVan_240"></td>
<td><textarea cols="100" name="TransitVan_240 comments" ng-model="edit.Comments" ></textarea></td>
</tr>
<tr>
<td width="300px">Transit Van 360</td>
<td><input name="TransitVan_360" ng-model="edit.TransitVan_360"></td>
<td><textarea cols="100" name="TransitVan_360 comments" ng- model="edit.Comments"></textarea></td> 
 </tr>
 <tr>
<td width="300px">Subaru Impreza</td>
<td><input name="Subaru_Impreza" ng-model="edit.Subaru_Impreza"></td>
<td><textarea cols="100" name="Subaru_Impreza comments" ng- model="edit.Comments"></textarea></td>
</tr>
</table>

<h3>Pick up and Drop Off Times</h3>
<br>
<table class="table table-bordered">
<tr>
<td width="300px">Pick Up Time:</td><td><input type="text"  name="Pick_Up_Time" value=""></td>
</tr>
<tr>
 <td width="300px">Drop off Time</td><td><input type="text" name="Drop_Off_Time" value=""></td>
</tr>
</table>
<br>

<h3>Personal Care Hours Pick Up/Drop Off</h3>
<table class="table table-bordered">
<tbody>
 <tr>
  <td>Monday</td>
  <td>Tuesday</td>
  <td>Wednesday</td>
  <td>Thursday</td>
  <td>Friday</td>
  <td>Saturday</td>
  <td>Sunday</td>
</tr>
<tr>
  <td><input type="text" name="Monday_Pick_Up" ng-model="edit.Monday_Pick_Up" placeholder="Pick Up Time"></td>
  <td><input type="text" name="Tuesday_Pick_Up" ng-model="edit.Tuesday_Pick_Up" placeholder="Pick Up Time"></td>
  <td><input type="text" name="Wednesday_Pick_Up" ng-model="edit.Wednesday_Pick_Up" placeholder="Pick Up Time"></td>
  <td><input type="text" name="Thursday_Pick_Up" ng-model="edit.Thursday_Pick_Up" placeholder="Pick Up Time"></td>
  <td><input type="text" name="Friday_Pick_Up" ng-model="edit.Friday_Pick_Up" placeholder="Pick Up Time"></td>
  <td><input type="text" name="Saturday_Pick_Up" ng-model="edit.Saturday_Pick_Up" placeholder="Pick Up Time"></td>
  <td><input type="text" name="Sunday_Pick_Up" ng-model="edit.Sunday_Pick_Up" placeholder="Pick Up Time"></td>
</tr>
<tr>
  <td><input type="text" name="Monday_Drop_Off" ng-model="edit.Monday_Drop_Off" placeholder="Drop Off Time"></td>
  <td><input type="text" name="Tuesday_Drop_Off" ng-model="edit.Tuesday_Drop_Off" placeholder="Drop Off Time"></td>
  <td><input type="text" name="Wednesday_Drop_Off" ng-model="edit.Wednesday_Drop_Off" placeholder="Drop Off Time"></td>
  <td><input type="text" name="Thursday_Drop_Off" ng-model="edit.Thursday_Drop_Off" placeholder="Drop Off Time"></td>
  <td><input type="text" name="Friday_Drop_Off" ng-model="edit.Friday_Drop_Off" placeholder="Drop Off Time"></td>
  <td><input type="text" name="Saturday_Drop_Off" ng-model="edit.Saturday_Drop_Off" placeholder="Drop Off Time"></td>
  <td><input type="text" name="Sunday_Drop_Off" ng-model="edit.Sunday_Drop_Off" placeholder="Drop Off Time"></td>
  </tr>
 </tbody>
 </table>
 <input type="submit" name="submit"  ng-click="saveEdit()"  />

 </form>
 <pre>{{edit | json}}</pre>


 <a   href="http://localhost:8080/stlc/index.php/transport/list_show_data/transport_vi ew">
 <button type="button" class="btn btn-primary">Back</button>
 </a>

 <script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
 <script type="text/javascript"   src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js">    </script>


 <script type="text/javascript">
 var app = angular.module('app',[]);

  app.controller('decontroller', function($scope,$http){
  $scope.edit=<?php echo json_encode($aggregate_data_view);?>;

  $scope.saveEdit = function(){
  console.log("hey i'm submitting!");
   console.log($scope.edit);

  $http.post('?php echo site_url("index.php/transport/saveData")?>',  $scope.edit).
success(function(data){console.log(":)") }).
error(function(data){
console.log(":(")
});

};


});



 </script>

  </body>
  </html>



Here is my Controller:


public function saveData()
{


}

it is empty now cause i really don't know what to do,nothing has worked.
  

Ответ №1:

На моей странице у меня есть три кнопки. Первые два создают случайные AVL данные на странице, а второй сохраняет эти данные в БД

HTML:

  <button data-ng-click="createAvl()">Create Avl</button>
 <button data-ng-click="create1000Avl()">Create 1000 Avl</button>
 <button data-ng-click="saveAvl()">Save Avl</button>
  

ngController:

 app.controller("myCtrl", function ($scope, $http) {    
    $scope.avl = [];   --here is where i save the avl

    $scope.avl.push({
        'tracker_avl_id': getRandomArbitrary(0, 1000000, 1),
        'plate_num': getRandomArbitrary(0, 10000, 1),
        'x_lat': getRandomArbitrary(-69, -66, 0),
        'y_long': getRandomArbitrary(8, 10, 0),
        'azimuth': getRandomArbitrary(0, 359, 1),
        'engine_status': engine,
        'gps_fix': gps_fix,
        'event_time': getRandomDate()
    });

    $scope.saveAvl = function () {
        $scope.ResponseDetails = 'Working...';   -- some variables to show progress
        $scope.startDate = getDate();
        $scope.startTime = new Date().getTime();
        $scope.timeEllapsed = null;

        -- use $.param jQuery function to serialize data from JSON 
        var data = $.param({
            avl_list: $scope.avl
        });

        var config = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
            }
        }        

        -- send the data to my webservice
        $http.post('/AvlApi/putTrackerAVL', data, config)
        .success(function (data, status, headers, config) {            
            var end = new Date().getTime() - $scope.startTime;
            $scope.timeEllapsed = 'milliseconds passed: '   end;
            $scope.ResponseDetails = data;
        })
        .error(function (data, status, header, config) {
            $scope.ResponseDetails = "Data: "   data  
                "<hr />status: "   status  
                "<hr />headers: "   header  
                "<hr />config: "   config;
        });
    };
  

Мой веб-сервис находится в IIS с использованием C#

 [HttpPost]
public JsonResult putTrackerAVL(List<avl> avl_list)
{
    try
    {
        avl_list.ForEach(car => db.avl.Add(car));
        db.SaveChanges();
    }
    catch (Exception ex)
    {
        return Json(new { status = "Fail", message = ex.InnerException });
    }

    return Json(new { status = "Success" });
}
  

Комментарии:

1. спасибо Хуан Карлос, но я не знаю, как бы я применил это к моему примеру? не могли бы вы, пожалуйста, пояснить?

2. А) Вам нужно привязать кнопку вашей html-страницы к функции в вашем контроллере angular. Save button Б) преобразуйте вашу модель в данные JSON C) Отправьте данные на ваш веб-сервис. D) Вам нужен веб-сервис, но это другой вопрос.