ng-repeat仅在

时间:2016-04-16 20:46:23

标签: javascript angularjs angularjs-ng-repeat

使用AngularJS是一种只添加一次项目的方法。对于下面这段代码,我说输入F并将其添加到项目列表中。有没有办法限制我或任何用户再次添加F?



<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
    <div ng-controller="MyCtrl">
        <ul>
            <li ng-repeat="item in items track by $index">{{item}}</li>
        </ul>
        <input ng-model="newItem" type="text"></input>
        <button ng-click="add(newItem)">Add</button>
    </div>
</div>

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

app.controller('MyCtrl', function($scope) {
    $scope.items = ["A", "B", "C", "D"];
    $scope.add = function(item) {
        $scope.items.push(item);
    };

});
</script>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:3)

<强> ES5

您必须在方法中手动检查。

$scope.add = function (item) {
    if ($scope.items.indexOf(item) === -1) {
        $scope.items.push(item);
    }
};

<强> ES6

您可以使用Set

  

Set对象允许您存储任何类型的唯一

$scope.items = new Set(["A", "B", "C", "D"]);

$scope.add = function (item) {
    $scope.items.add(item);
};

答案 1 :(得分:0)

在调用push()函数以在数组中添加新项之前,您可以搜索是否在数组中找到相同的项。

在这种情况下,我会像这样编辑代码:

app.controller('MyCtrl', function($scope) {
    $scope.items = ["A", "B", "C", "D"];

    $scope.add = function(item) {
        var found = false;

        for(var i = 0; i< $scope.items.length; i++){
          if(item == scope.items[i])
            found = true;
            return; //end the for loop
        }

        //new item not found in the array
        if(!found) $scope.items.push(item);
    };

});

答案 2 :(得分:0)

您可以使用JavaScript Array.prototype.some检查该元素是否已经存在并根据该内容添加:

$scope.add = function(item) {

    if (!$scope.items.some(isAlreadyPresent)) {
      $scope.items.push(item);
    } else {
      console.log('item already present');
    }

    function isAlreadyPresent(ele) {
      return ele === item;
    }
};

有关somehttps://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/some

的更多详情,请参阅MDN