使用 ng-repeat 中使用的 ng-click 更改布尔值

Changing value of a boolean using ng-click used inside a ng-repeat

我正在使用 ng-repeat 在 div 内的 html 页面上显示一些数据。在 div 我有一个按钮来隐藏每个 div 的内容 seperately.Here 是我的 html 文件的简化版本。

<body ng-app="task" ng-controller="repeat">
    <div ng-repeat='x in array' ng-show="{{ x.show }}">
      <p>{{ x.text }}
      </p>
  <button ng-click="toggle()">Hide</button>
    </div>
</body>

我的.js文件中的代码如下

var app = angular.module('task');
app.controller('repeat',function($scope){
    $scope.array = [{
        show: true,
        text:'Sample Text 1'},
      { 
        show: true,
        text:'Sample Text 2'},
      { 
        show: true,
        text:'Sample Text 3'}];

    $scope.toggle = function(){
       $scope.array.show = false ;
      };
})

任何人都可以建议我进行必要的更改,以便在单击我的 div 中的按钮时,特定的 div 会被隐藏。

我想我在通过 ng-click

调用 function toggle() 时引用数组的特定元素时犯了一个错误

将您的元素作为参数放入切换函数中。

<button ng-click="toggle(x)">Hide</button>

并像这样在控制器中更改它:

$scope.toggle = function(x){
    x.show = !x.show;
};

无需调用控制器中的函数即可轻松实现:

<body ng-app="task" ng-controller="repeat">
  <div ng-repeat='x in array' ng-show="showDetail">
    <p>{{ x.text }}</p>
      <button ng-click="showDetail != showDetail">Hide</button>
  </div>
</body>

如果点击隐藏,上面的方法也会隐藏按钮。如果你想隐藏你的内容并再次显示它,下面的代码可以实现:

<body ng-app="task" ng-controller="repeat>
  <div ng-repeat='x in array'>
    <div class="content" ng-show="showContent">
      <p>{{ x.text }}</p>
    </div>
    <div class='btn btn-control'>
      <button ng-click="showContent != showContent"> Hide </button>
    </div>
  </div>
</body>

好吧,我找到了一种真正满足我需求的方法,谢谢大家的建议。这是我实际使用的代码:

<body ng-app="task" ng-controller="repeat">
 <div ng-repeat='x in array' ng-hide="x.show">
  <p>{{ x.text }}
  </p>
  <button ng-click="toggle($index)">Hide</button>
 </div>
</body>

在我的 js 文件中,我是这样使用它的:

var app = angular.module('task');
app.controller('repeat',function($scope){
 $scope.array = [{
    show: true,
    text:'Sample Text 1'},
  { 
    show: true,
    text:'Sample Text 2'},
  { 
    show: true,
    text:'Sample Text 3'}];

 $scope.toggle = function(){
   $scope.array[index].show = false ;
  };
})

在你的html传球中

   <button ng-click="toggle(x.$index)">Hide</button>

在 js 中

  $scope.toggle = function(index){
  $scope.array[index].show = !$scope.array[index].show;
  };