Почему ng-repeat ведет себя странно с автоинкрементным идентификатором?

У меня есть форма, которая вставляется в базу данных MySQL.
POST-запросы и GET-запросы работают отлично.

Я решил добавить столбец id в таблицу MySQL.
Оператор SQL, используемый для добавления моего столбца id, был:
ALTER TABLE thestuff ADD COLUMN id INT AUTO_INCREMENT UNIQUE FIRST;

До того, как я добавил столбец идентификатора в таблицу, когда я ввел дату и содержимое и нажал кнопку «Отправить», выборка работала бы отлично, и сразу же отобразились бы дата и содержимое.

Но теперь, когда я добавил столбец идентификатора, когда я добавляю дату и контент и нажимаю «отправить», дата и контент будут отображаться немедленно, но также и идентификатор, но по какой-то причине это не так.

Я перепробовал все и не могу понять, почему Идентификатор имеет задержку.
Единственный способ получить идентификатор для показа — обновить страницу.

Любые предложения будут очень признательны!
Спасибо!


До
До


После
После


HTML

<body ng-app="myApp">

<div ng-controller="insertController">
<h2> What I learned today </h2>
<form>
Date <br>
<input type="text" ng-model="date"><br><br>
Content <br>
<textarea rows="10" cols="50" ng-model="content"></textarea><br><br>
<input type="button" value="Submit" ng-click="insertdata()">
</form>
</div>

<div ng-controller="fetchController"><br>
<span ng-repeat="item in results">
<div class="card">
id: {{item.id}}<br>
<span class="bold-underline">{{item.date}}</span><br>
{{item.content}}
<button class="deleteButton" ng-click="deleteThisItem()"> x </button>
</div>
<br><br>
</span>
</div>

</body>

fetch.php

<?php
header('Access-Control-Allow-Origin: *'); // clientside(Node) <-> serverside(PHP)

$theConnection = new mysqli("localhost", "root", "", "storestuff");

if($theConnection->connect_error) {
printf("Connection failed: %s\n", $theConnection->connect_error);
exit();
}

$query = "SELECT * FROM thestuff";
$theData = array();

if($result = $theConnection->query($query)) {
while($row = mysqli_fetch_array($result)) {
$theData[] = array(
'id'=>$row['id'],
'date'=>$row['date'],
'content'=>$row['content']);
}
echo json_encode($theData); // Echo the output for the controller to access
$result->free(); // Free the result set
}
else {
echo "0 results.";
}
$theConnection->close(); // Close the connection
?>

fetchController.js

var size = 0;
var count = 0;

app.controller('fetchController', function ($scope, $http, resultsService) {
$http.get('http://localhost/storestuff/fetch.php')
.then(function successCallback(response) {
size = (response.data).length;
while(count < size) {
var id = response.data[count].id;
var date = response.data[count].date;
var content = response.data[count].content;
resultsService.addItem(id, date, content);
count++;
}
size = 0;
count = 0;
$scope.results = resultsService.getItems();
});
});

Result.js

app.service('resultsService', function() {
var results = new Array();

var addItem = function(id, date, content) {
var obj = new Object();
obj['id'] = id;
obj['date'] = date;
obj['content'] = content;
results.push(obj);
}

var getItems = function() {
return results;
}

var deleteItem = function() {

}

return {
addItem: addItem,
getItems: getItems,
deleteItem: deleteItem
};

});

insert.php

<?php

header('Access-Control-Allow-Origin: *');

$theConnection = mysqli_connect("localhost", "root", "", "storestuff");
if(mysqli_connect_errno()) {
echo "Failed to connect to MySQL.";
}

$theData = json_decode(file_get_contents('php://input'));
$date = mysqli_real_escape_string($theConnection, $theData->date);
$content = mysqli_real_escape_string($theConnection, $theData->content);

mysqli_query($theConnection, "INSERT INTO thestuff(date, content) VALUES('$date', '$content')");

mysqli_close($theConnection);

?>

insertController.js

var app = angular.module('myApp', []);

app.controller('insertController', function($scope, $http, resultsService) {
$scope.insertdata = function() {
$http({
method: 'POST',
url: 'http://localhost/storestuff/insert.php',
data: {'date':$scope.date, 'content':$scope.content, 'in':'json-format'},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(res) {
console.log("Successful response", res)
resultsService.addItem($scope.date, $scope.content);
$scope.date = "";
$scope.content = "";
})
.catch(function(err) {
console.error("Error with POST", err);
});
}
});

0

Решение

в insertController вам не хватает id параметр

resultsService.addItem($scope.date, $scope.content); //wrong

следовательно дата назначается id,

Правильный:
resultsService.addItem(res.id, $scope.date, $scope.content);

2

Другие решения

Других решений пока нет …