2

Angular を使用して小さな練習用の to-do リスト アプリを作成しています。新しいタスクを作成するためのフォームを作成しましたが、正常に更新されています。「削除」というタイトルのすべてのタスクに対して生成されるボタンがあります。Todoリストからそのタスクを具体的に削除するボタンを作成したいと思います。htmlコードは次のとおりです。

<div ng-controller="todoListController">
    <ul>
        <li ng-repeat="task in taskList">
            <p>
                {{task.name}}: {{task.description}}
                <button ng-click="killtodo()"> Remove </button>
            </p>
        </li>
        <hr>
        <h3> Display: </h3>
        <li>
            <p>
                {{task}}: {{taskDescription}}
            <p>
        </li>
    </ul>
    <hr>
    <form ng-submit="addto()">
        <input type="text" ng-model="task" placeholder="Enter a task name.">
        <input type="text" ng-model="taskDescription" placeholder="Enter the description.">
        <input class="btn-primary" type="submit" value="add">
    </form>
</div>

Javascript コード:

function todoListController($scope) {
$scope.taskList = [
{"name": "Task List",
 "description": "Make a Task List."}
];

$scope.addto = function() {
    $scope.taskList.push({name:$scope.task, description:$scope.taskDescription});
    $scope.task = '';
    $scope.taskDescription = '';
};

$scope.killtodo = function(name) {
};

}

どんな提案も素晴らしいでしょう、ありがとう。

4

1 に答える 1

7

ng-repeat の使用中に $index という変数にアクセスできるため、次のようなことができます。

<li ng-repeat="task in taskList">
    <p>
        {{task.name}}: {{task.description}}
        <button ng-click="killtodo($index)"> Remove </button>
    </p>
</li>

そして、コントローラーで:

function todoListController($scope) {
    //other code
    $scope.killtodo = function($index){
        $scope.taskList.splice($index, 1);
    }
}

上部のドキュメントで利用可能な詳細な説明があります (使用できる他の変数を含む): http://docs.angularjs.org/api/ng.directive:ngRepeat

于 2012-12-20T01:16:49.907 に答える