2016-02-27 32 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