Patrick
Patrick

Reputation: 4298

Toggle between two functions when button clicked.

I have the following button which i am using as a toggle.

<button ng-click="togglefunction()">Toggle Data</button>

Here is the toggle part which should work

 $scope.toggleToolPanel = function () {
        // need to put below 2 functions here so that when user clicks 1st time, function 1 executes. when user clicks again, function 2 executes and so on. 
    };

These are 2 functions which should get executed alternatively inside the toggleFunction

 function function1(params) { 
                return '<span  >' + data + '</span>';
    }

function function2(params) { 
                return '<span  >' + data *100 + '</span>';
    }

Upvotes: 1

Views: 1068

Answers (3)

Suneet Bansal
Suneet Bansal

Reputation: 2702

Cleaner code is attached below:

angular.module('mainModule', [])
         .controller('MainCtrl', ['$scope', function($scope) {
           $scope.toggle = function() {
        $scope.isToggled = !$scope.isToggled;
        var params = $scope.isToggled;

                $scope.isToggled ? toggleIn(params) : toggleOut(params);

           };

           function toggleIn(params) {
        console.log(params);
       }

           function toggleOut(params) {
        console.log(params);
           }


         }]);

<body ng-app="mainModule">
<div ng-controller="MainCtrl">
  <input type="button" value="Toggle" ng-click="toggle()" />
</div>

</body>

Upvotes: 1

Ronnie Smith
Ronnie Smith

Reputation: 18565

Toggle a class on the button element each time it's clicked. See classList.toggle. In your click event handler, use classList.contains to look for the presence of toggle. If there do x, if not do y.

Upvotes: 1

Lex
Lex

Reputation: 7194

Add this to your controller:

$scope.firstFunction = false;

Then change your toggleToolPanel to the following:

$scope.toggleToolPanel = function() {
    $scope.firstFunction = !$scope.firstFunction;
    if($scope.firstFunction) {
        function1(params);
    } else {
        function2(params);
    }
};

Upvotes: 2

Related Questions