ng-repeat隐藏重复项

时间:2017-11-12 14:15:36

标签: javascript arrays angularjs

我有一系列重复的项目,我想只隐藏其中一项来自我的ng-repeat。

如何在点击时仅隐藏其中一个重复项?

我可能错过了一些东西,但我很难找到它。

Plunker example



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

app.controller('MainCtrl', function($scope) {
  var users = [{name: 'toto', hide:false},{name: 'titi', hide:false},{name: 'tutu', hide:false},{name: 'tata', hide:false}];
  
  $scope.doubledUsers = [].concat(users, users);
  
  $scope.hideUser = function(user){
    user.hide = true;
  }
});

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
    <script src="app.js"></script>
  </head>

    <body ng-controller="MainCtrl">
    <div ng-repeat="user in doubledUsers | orderBy: 'name' track by $index">
      <p ng-hide="user.hide" ng-click="hideUser(user)">Hello {{user.name}}! - id={{$index+1}}</p>      
    </div>

  </body>

</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

实际上你的逻辑是正确的,问题出在这一行,

$scope.doubledUsers = [].concat(users, users);

当你这样做时,同样的引用被复制到用户,所以当你隐藏时,两个元素被隐藏。

<强>样本

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

app.controller('MainCtrl', function($scope) {
  $scope.users = [{name: 'toto', hide:false},{name: 'titi', hide:false},{name: 'tutu', hide:false},{name: 'tata', hide:false}];
  
 // $scope.doubledUsers = [].concat(users, users);
  
  $scope.hideUser = function(user){
    user.hide = true;
  }
});
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
    <script src="app.js"></script>
  </head>

    <body ng-controller="MainCtrl">
    <div ng-repeat="user in users | orderBy: 'name' track by $index">
      <p ng-hide="user.hide" ng-click="hideUser(user)">Hello {{user.name}}! - id={{$index+1}}</p>      
    </div>

  </body>

</html>