steiacopi
steiacopi

Reputation: 27

Dynamically change button label inside ng-repeat

Consider a simple ng-repeat which creates a directive in each iteration. Each directive contains a button that triggers a function. These buttons should have the label set to "Show", and should change to "Hide" when the button is clicked. When I click on a button I want to check if there are other buttons set to "hide": if yes, they should revert to "show". Basically my goal is to only have one button with the label set to "Hide", others should always be "Show". How can I do that?

 <div ng-repeat="campaign in $root.transactions">
    <my-directive campaign='campaign' index='$index></my-directive>
 </div>

myDirective.html:

<div>
..some stuff...
<button ng-click="toggleDetail()">{{labelButton}}</button>
</div>

js:

$scope.labelButton = 'Show';
$scope.detailOpened = false;
$scope.labelButton = 'Show';
$scope.$root.selectedIndex = -1;

$scope.toggleDetail = function($event, index){  

        ...do stuff...


        $scope.detailOpened = !$scope.detailOpened;
        $scope.$root.selectedIndex = index;     
        $(element).toggleClass('selectedActivity');         

        if($scope.detailOpened === false) {
            $scope.labelButton = 'Show';
        }else {
            $scope.labelButton = 'Hide';
        }                       
    };

Upvotes: 0

Views: 272

Answers (1)

gm2008
gm2008

Reputation: 4325

With ng-repeat, you'll need an array in $scope. Using directive will do, but may not be necessary.

I have made a jsfiddle here: http://jsfiddle.net/goodman/z9kg0md0/15/embedded/result/

I wonder if this is what you want. Codes are here:

    angular.module("MyApp",[])
    .controller( 'myController', [ '$scope', function( $scope ){
      $scope.buttons = [
        { detailOpened: false, label: 'Show1'},
        { detailOpened: false, label: 'Show2'},
        { detailOpened: false, label: 'Show3'},
        { detailOpened: false, label: 'Show4'},
        { detailOpened: false, label: 'Show5'}    
      ];

      $scope.toggleDetail = function(index){  
        $scope.buttons[index].detailOpened = !$scope.buttons[index].detailOpened;      
        if(!$scope.buttons[index].detailOpened) {
              $scope.buttons[index].label = 'Show';
        }else {
              $scope.buttons[index].label = 'Hide';
        }   
            if( $scope.buttons[index].detailOpened ){
          for( var i = 0; i < $scope.buttons.length ; i++ ){
            if( i != index && $scope.buttons[i].detailOpened) {
                $scope.buttons[i].detailOpened = false;      
              $scope.buttons[i].label = 'Show';
            }   
          }
        }
      };
    }]);

and html:

<div ng-app="MyApp" ng-controller="myController">

  <div ng-repeat="button1 in buttons">
    <button ng-click="toggleDetail($index)">
      {{button1.label}}    
    </button>
   </div>
</div>

Upvotes: 1

Related Questions