I am facing an issue with my page where I display a list of titles (referred to as suggestions in my app) directly fetched from a database using a service. Additionally, there is a form for users to input new titles. The problem arises when a new title is entered into the form - although the data gets inserted into the database, the page does not refresh properly. The title ends up being inserted twice in the database and also displayed twice on the view page. Even if I manually delete the first title from the database and insert a second one, the first title still appears on the page.
Below is an excerpt from my controller:
app.controller('HomeController', [
'$scope',
'$http',
'get_suggestions',
function($scope, $http, get_suggestions) {
$scope.addSuggestion = function() {
var title = $scope.newsuggest.title;
if (!title || title === "") {
$scope.error = "Enter a suggestion";
return;
} else {
$http.post('add_suggestions.php', {
title: $scope.newsuggest.title
}).success(function(data, status, headers, config) {
$scope.posts.push({
title: title,
upvotes: 0,
comments: []
});
$scope.newsuggest.title = '';
$scope.error = '';
$scope.$apply();
$route.reload();
})
.error(function(data, status) {
$scope.errors.push(status);
});
}
}
get_suggestions.success(function(data) {
$scope.posts = data;
});
}
]);
Here is a snippet of my view page:
<div class="container">
<div ng-repeat="post in posts | orderBy:'upvotes'" class="col-md-6" style="clear:both; padding-bottom:20px;">
<p class="title">{{post.title}} </p>
<p>Votes: {{post.upvotes}} </p>
</div>
</div>
<div class="container">
<div class="col-md-6" style="clear:both; padding-bottom:20px;">
<form ng-submit="addSuggestion()" style="margin-top: 50px">
<h3> Send a suggestion </h3>
<div class="form-group">
<input type="text" class="form-control" name="title" ng-model="newsuggest.title"></input>
<div>{{error}}</div>
</div>
<button type="submit" ng-click="addSuggestion();" class="btn btn-primary">Send</button>
</form>
</div>
</div>