2016-02-27 49 views
2
  • 截图附接。

我学习angularJS。 而我找不到方法来删除'删除'按钮被点击的选定项目。如何获取所选的特定项目?

有没有办法做到这一点?

代码附:

 <ul class="unstyled"> 
      <li ng-repeat="todo in todos"> 
       <input type="checkbox" ng-model="todo.done"> 
       <span class="done-{{todo.done}}">{{todo.text}}</span> 
       <button class="btn" ng-click="removeTodo()">Remove</button> 
      </li> 
     </ul> 

enter image description here

+0

如何使待办事项到你的'removeTodo()'方法,然后在方法(我假设在一个关联的控制器),从你的列表中删除该项目。 – jpmcc

+0

好..怎么做? :(我刚开始学习..找不到方法) – Yanshof

+0

所以,在'ng-repeat'中你有'todo'对象,所以在你的'ng-click'中你可以有'removeTodo(todo)'' 。然后在你的'removeTodo'方法中,你可以选择'todo'对象,并且可以在你的对象数组'todos'中找到该项目的索引,并将其拼接出来。这一点只是标准的JavaScript而不是任何特别的Angular – jpmcc

回答

3

var app = angular.module("app" , []); 
 
app.controller("MyCtrl" , function($scope){ 
 
    
 
    $scope.todos = [ 
 
    {"text" :"Learn AngularJS","done":false},{"text" :"build an app","done":false}]; 
 
    
 
    $scope.removeTodo = function(index) { 
 
    $scope.todos.splice(index,1); 
 
    
 
    } 
 
    
 
    $scope.removeTodo2 = function(todo) { 
 
    var index = getByValue($scope.todos,todo); 
 
    $scope.todos.splice(index,1); 
 
    
 
    } 
 
    
 
    $scope.addTodo = function(todo){ 
 
    var toDoObject = {"text":todo,"done":false}; 
 
    $scope.todos.push(toDoObject); 
 
    
 
    }; 
 
    
 
    $scope.done = function(todo){ 
 
    angular.forEach($scope.todos,function(index,todo1){ 
 
     if(todo == todo1) 
 
      $scope.todos[index].done = !$scope.todos[index].done; 
 
     }) 
 
    
 
    
 
    } 
 
    
 
    function getByValue(arr, value) { 
 

 
    for (var i=0, iLen=arr.length; i<iLen; i++) { 
 

 
    if (arr[i].text == value) return i; 
 
    } 
 
} 
 
    
 
    });
.done{ 
 
    text-decoration: line-through; 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="app" ng-controller="MyCtrl"> 
 
    
 
<ul class="unstyled"> 
 
      <li ng-repeat="todo in todos track by $index"> 
 
       <input type="checkbox" ng-model="todo.done" > 
 
       <span ng-class="{'done' : todo.done == true}">{{todo.text}}</span> 
 
       <button class="btn" ng-click="removeTodo($index)">Remove</button> 
 
       <button class="btn" ng-click="removeTodo2(todo.text)">Remove2</button> 
 
      </li> 
 
     </ul> 
 
    <input type="text" ng-model="todo"> 
 
    <input type="button" ng-click = "addTodo(todo)" value="Add"> 
 
    
 
    </div>

+0

@Yanshof我编辑我的答案。如果你为你工作,请接受它。谢谢。 –

+0

是的,我猜在'$ index'中传递好得多。 – jpmcc

+1

但是,如果使用任何过滤器,不要传递'$ index' ...将不会是正确的索引。更安全地做你自己的索引 – charlietfl