如何让Angular有一个click事件将dom的一部分带到函数中?

sai*_*lie 2 angularjs

我正在使用Angular创建一个小型练习待办事项列表应用程序.我创建了一个用于创建新任务的表单,并且它们正在更新.我为每个标题为"删除"的任务生成了一个按钮.我想让按钮从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>
Run Code Online (Sandbox Code Playgroud)

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) {
};
Run Code Online (Sandbox Code Playgroud)

}

任何建议都会很棒,谢谢.

Mat*_*erg 7

您可以在使用ng-repeat时访问名为$ index的变量,因此您可以执行以下操作:

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

然后在你的控制器中:

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

顶部的文档中提供了更多描述(包括您可以使用的其他变量):http://docs.angularjs.org/api/ng.directive:ngRepeat