Search code examples
angularjsangularjs-ng-repeatng-show

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


I am displaying some data on my html page inside a div using ng-repeat. Inside the div I have a button in order to hide the content of each div seperately.Here is a simplified version of my html file.

<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>

the code in my .js file is as follows

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 ;
      };
})

Can anyone suggest me the required changes so that on clicking the button inside my div , that particular div gets hidden.

I think I am committing a mistake in referencing the particular element of the array while calling the function toggle() through ng-click


Solution

  • Well I found a way to actually cater my needs , thank you all for your suggestions. Here is the code I actually used:

    <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>
    

    and in my js file I used it like this:

    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 ;
      };
    })