我的待办事项列表有问题。我希望当我输入新项目时,它出现在列表项目的顶部,而不是列表项目的下方。我已将 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 = '';
};
有什么解决办法吗?
最佳答案
使用unshift()
将项目添加到数组前面而不是 push()
并通过 -$index 删除 track
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>
关于javascript - 使用 Angular 将最新项目置于待办事项列表顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34413169/