2016-08-01 13 views
0
<!DOCTYPE html> 
<html> 
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css"> 
<body> 

<script> 
var app = angular.module("myShoppingList", []); 
app.controller("myCtrl", function($scope) { 
    $scope.products = ["Milk", "Bread", "Cheese"]; 
    $scope.addItem = function() { 
     $scope.errortext = ""; 
     if (!$scope.addMe) {return;} 

      $scope.products.push($scope.addMe); 

    } 
    $scope.removeItem = function (x) { 
     $scope.errortext = ""; 
     $scope.products.splice(x, 1); 
    } 
}); 
</script> 

<div ng-app="myShoppingList" ng-cloak ng-controller="myCtrl" class="w3-card-2 w3-margin" style="max-width:400px;"> 
    <header class="w3-container w3-light-grey w3-padding-16"> 
    <h3>My Shopping List</h3> 
    </header> 
    <ul class="w3-ul"> 
    <li ng-repeat="x in products" class="w3-padding-16">{{x}}<span ng-click="removeItem($index)" style="cursor:pointer;" class="w3-right w3-margin-right">×</span></li> 
    </ul> 
    <div class="w3-container w3-light-grey w3-padding-16"> 
    <div class="w3-row w3-margin-top"> 
     <div class="w3-col s10"> 
     <input placeholder="Add shopping items here" ng-model="addMe" class="w3-input w3-border w3-padding"> 
     </div> 
     <div class="w3-col s2"> 
     <button ng-click="addItem()" class="w3-btn w3-padding w3-green">Add</button> 
     </div> 
    </div> 
    <p class="w3-padding-left w3-text-red">{{errortext}}</p> 
    </div> 
</div> 

</body> 
</html> 

我已經看到了這個W3Schools的代碼我的問題是我想補充相同的產品,其已經在列表中,如果我嘗試添加產品,已經在列表中的產品不會增加列表或數組加入同一項目入陣

回答

1

值肯定會被推入陣,但ng-repeat不會允許重複,因此,你不看到在DOM的改變,使用track by $index允許重複

ng-repeat="x in products track by $index"