Как запретить добавление одинаковых значений в массив ?
Как запретить добавление одинаковых значений в массив ?
![]() <!DOCTYPE html> <html ng-app="app"> <head> <title>Tony's Pizza</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjV ME1fgjWPGmkzs7" crossorigin="anonymous"> </head> <body ng-controller="pizzaController"> <div class="container"> <h3>Topping Search</h3> <input type="text" class="form-control" ng-model="model.search" > <br> <div class="alert alert-success" ng-show="model.showAdded"> Topping added. <input type="button" value="close" ng-click="hideAdded()"> </div> <div class="alert alert-danger" ng-show="model.search && (model.availableToppings | filter:model.search).length == 0"> No results. </div> <div ng-hide="model.search"> Enter the search criteria above. </div> <div ng-repeat="t in model.availableToppings | filter:model.search"> <span ng-click="addTopping(t)">{{t}}</span> </div> <h3 ng-show="model.toppings.length > 0">Selected Toppings</h3> <div ng-repeat="t in model.toppings"> {{t}}<span ng-click="removeItem($index)" class="glyphicon glyphicon-remove"></span> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script> <script> var app = angular.module('app', []); app.controller('pizzaController', [ '$scope', function ($scope) { $scope.model = { title: 'Pizza Builder', availableToppings: [ 'Cheese', 'Pepperoni', 'Bacon', 'Pineapple', 'Sausage', 'Ham', 'Chicken', 'Mushrooms', 'Onion', 'Olives', 'Green Peppers' ], toppings: [], showAdded: false }; $scope.addTopping = function (topping){ $scope.model.toppings.push(topping); $scope.model.search = ""; $scope.model.showAdded = true; } $scope.hideAdded = function (){ $scope.model.showAdded = false; } $scope.removeItem = function (z) { $scope.model.toppings.splice(z, 1); } } ]); </script> </body> </html> |
if (~$scope.model.toppings.indexOf(topping)) return; |
Спасибо за помощь ! ;)
|
Часовой пояс GMT +3, время: 18:05. |