使用Angular在待办事项列表中创建最新项目

时间:2015-12-22 10:06:00

标签: javascript angularjs

我的待办事项列表存在问题。我想在输入新项目时,它显示在列表项目的顶部,而不是列表项目下方。我放了track by -$index但它没有用

index.html代码段

<ul class="unstyled">
   <li ng-repeat="todo in todos track by -$index">
       <input type="checkbox" ng-model="todo.done">
       <span class="done-{{todo.done}}">{{todo.text}}</span>
    </li>
</ul>

controller.js片段

app.controller('TodoListController', ['$scope', function($scope) {
    $scope.todos = [];

    $scope.addTodo = function() {
        $scope.todos.push({text:$scope.todoText, done:false});
        $scope.todoText = '';
    };

对此有什么解决方案吗?

2 个答案:

答案 0 :(得分:2)

使用unshift()将项目添加到您的数组而不是push()并删除track by -$index

的Javascript

app.controller('TodoListController', ['$scope', function($scope) {
    $scope.todos = [];

    $scope.addTodo = function() {
        $scope.todos.unshift({text:$scope.todoText, done:false});
        $scope.todoText = '';
    };

HTML

<ul class="unstyled">
   <li ng-repeat="todo in todos">
       <input type="checkbox" ng-model="todo.done">
       <span class="done-{{todo.done}}">{{todo.text}}</span>
    </li>
</ul>

答案 1 :(得分:1)

来自@nipeco的解决方案工作正常,但它改变了出于演示目的的逻辑,我个人不建议这样做。

我认为最好推送并使用过滤器orderBy + reverse来获得所需的输出。

<li ng-repeat="todo in todos | orderBy:'-$index':reverse">

希望它有所帮助!