Reputation: 566
I have a simple app that adds an item to a list, but the item gets added to the bottom of the list rather than the top. Is there a way to get it adding to the top such as prepending it? Let me know if you need more code to look at. Any help is greatly appreciated. Thank you.
The HTML
<!-- LOOP OVER THE TODOS IN $scope.todos -->
<div class="checkbox" ng-repeat="todo in todos">
<label>
<input type="checkbox" ng-click="deleteTodo(todo._id)"> {{ todo.text }}
</label>
</div>
Some of the Angular.js
// when submitting the add form, send the text to the node API
$scope.createTodo = function() {
$scope.loading = true;
// validate the formData to make sure that something is there
// if form is empty, nothing will happen
if ($scope.formData.text != undefined) {
// call the create function from our service (returns a promise object)
Todos.create($scope.formData)
// if successful creation, call our get function to get all the new todos
.success(function(data) {
$scope.loading = false;
$scope.formData = {}; // clear the form so our user is ready to enter another
$scope.todos = data; // assign our new list of todos
});
}
};
// create todo and send back all todos after creation
app.post('/api/todos', function(req, res) {
// create a todo, information comes from AJAX request from Angular
Todo.create({
text : req.body.text,
done : false
}, function(err, todo) {
if (err)
res.send(err);
// get and return all the todos after you create another
Todo.find(function(err, todos) {
if (err)
res.send(err)
res.json(todos);
});
});
});
Upvotes: 0
Views: 707
Reputation: 7892
Rewriting the answer after some more information was obtained from the comments.
The problem is that the todos is an object rather than an array. In Angular, when iterating (ng-repeat) over an object the keys of the objects are used to determine the order of the items. This is typically not what you want when dealing with lists of things (todos). So the way to approach this would be to change the back-end so that it returns an array.
I won't go too much into mongodb details on how this is done, but generally you may either store each todo as its own document and return a get on all the documents, or you can store one document with a todos property (which is a BsonArray) and return that document.
Upvotes: 1