2016-04-10 25 views
0

我有一個Angular應用程序,我試圖正確工作。顯然只有一行代碼會使它工作,但我不知道它是什麼。無論如何,我仍然在學習Angular,而且我對JavaScript並不擅長。我已經這樣做了,任何進入輸入的東西都會被添加到列表中。但是當我點擊一個按鈕來刪除一個項目時,它只會刪除它們中的所有項目。我能做些什麼來解決它?Angular購物清單 - 刪除單個項目

<body ng-app="myApp"> 
     <div ng-controller="GroceryController"> 
      <header> 
       <h1>Matt's Grocery List</h1> 

       <div> 
        <form ng-submit="addItem()"> 
         <div> 
          <input type="text" ng-model="newItem" placeholder="New things"> 
          <button type="submit">Save</button> 
         </div> 
        </form> 
       </div> 
      </header> 
      <section id="list"> 
      <p>"{{ newItem }}"</p> 

      <div> 
       <h4>{{ groceries.length }} total items</h4> 
       <table> 
        <tr ng-repeat="gro in groceries"> 
         <td>{{gro}}</td> 
         <td> 
          <button class="remove" ng-click="removeItem(gro)">&times;</button> 
         </td> 
        </tr> 
       </table> 
      </div> 
      </section> 
     </div> 
    </body> 

var app = angular.module('myApp', []); 

app.controller('GroceryController', function($scope){ 

    $scope.groceries = ['Nails', 'Pipe', 'Wood']; 

    $scope.addItem = function() { 
     $scope.groceries.push($scope.newItem); 
     $scope.newItem = ''; 
    } 

    $scope.removeItem = function(item) { 
     var idx = $scope.groceries.indexOf(item); 
      $scope.groceries.splice(idx.l); 
    } 
}); 

我有一個JSfiddle在這裏,但我實際上不能讓它在那裏運行。當我嘗試在瀏覽器中執行它時,它運行得很好。也許你可以讓它運行,然後你可以找出問題。我真的很感激它!謝謝。

https://jsfiddle.net/bt08rbqt/

回答

1

。在你的拼接方法的錯誤。使用它作爲如下─

$scope.removeItem = function(item) { 
    $scope.groceries.splice($scope.groceries.indexOf(item),1); 
} 
+0

你也可以用它自己的方式與接續方法 –

+0

謝謝你這麼多的內部IDX變量之後逗號(,)代替點(。)!這解決了它!你真棒! –

+0

不客氣。另外,這裏是你更新的[jsfiddle](https://jsfiddle.net/bt08rbqt/1/)。你的腳本在角庫之前被加載。加載類型已更改爲無換行 - 來自onLoad的 –