javascript - 使用 Angular 将项目添加到列表顶部

标签 javascript arrays angularjs list prepend

我有一个简单的应用程序,可以将项目添加到列表中,但该项目被添加到列表的底部而不是顶部。有没有办法让它添加到顶部,例如预先添加它?如果您需要查看更多代码,请告诉我。任何帮助是极大的赞赏。谢谢。

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/

相关文章:

javascript - 如何让firefox报javascript错误?

javascript - 所有ajax请求完成后如何调用警报?

javascript - 如何确保脚本运行一次且仅运行一次

javascript - jQuery .toggle() + addClass() 似乎没有达到预期的效果

python - 在 Python 的 scipy/numpy 中有效地找到非零区间?

访问二维数组的正确方法 - C

java - 如何在Java中实现固定大小的 "list"?

javascript - 垂直全页 slider ,如 Angular 中的 www.tumblr.com

html - Angular : how to initialize textarea with default value

javascript - 使用 jQuery 对 AngularJS 生成的表行求和