我有一个简单的应用程序,可以将项目添加到列表中,但该项目被添加到列表的底部而不是顶部。有没有办法让它添加到顶部,例如预先添加它?如果您需要查看更多代码,请告诉我。任何帮助是极大的赞赏。谢谢。
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>
一些 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);
});
});
});
最佳答案
从评论中获得更多信息后重写答案。
问题在于待办事项是一个对象而不是数组。在 Angular 中,当对对象进行迭代(ng-repeat)时,对象的键用于确定项目的顺序。在处理事物列表(待办事项)时,这通常不是您想要的。因此,解决此问题的方法是更改后端,使其返回一个数组。
我不会过多介绍 mongodb 的详细信息,但通常您可以将每个待办事项存储为自己的文档并返回所有文档的 get,或者您可以使用 todos 属性存储一个文档(这是一个 BsonArray)并返回该文档。
关于javascript - 使用 Angular 将项目添加到列表顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24706197/