1

I want to change a button name once it is clicked. There are two functions differently Add and Subtract. first-time button name is 'Add', when it clicked it should execute add number function and then name dynamically change button name to Subtract, and once I clicked to subtract it should execute subtract function and again the name of a button come to Add which is previous. How can I do this? how to call a different function like add function when button toggle is add and vice versa.

now I can toggle between two buttons but facing issues with calling add and subtract functions.

<div ng-app="myModule">
  <div ng-controller="myController">
    <button ng-click="toggle = !toggle">
      {{ toggle ? 'Add' : 'Subtract' }}
    </button>
  </div>
</div>

2 Answers 2

1

Varsha, Could you please check this working fiddle. Do you want this?

Explanation: You can use a flag (functionToBeCalled in this case) to call the targeted function and switch the text of the button.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="personCtrl">

 <button ng-click="functionToBeCalled == 'Add' ? add() : substract();">
      {{ functionToBeCalled }}
    </button>
<br>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
    $scope.functionToBeCalled = "Add";
    $scope.add = function() {
    	$scope.functionToBeCalled = "Substract";
        alert('Add is clicked');
    };
    
    $scope.substract = function() {
    	$scope.functionToBeCalled = "Add";
        alert('Substract is clicked');
    };
});
</script>

</body>
</html>

Sign up to request clarification or add additional context in comments.

Comments

0

You probably want to have 2 buttons defined and show one of them at a time using ng-if. ng-if removes the button from the DOM if the condition is not met. See the official documentation: https://docs.angularjs.org/api/ng/directive/ngIf

<div ng-app="myModule">
  <div ng-controller="myController">
    <button ng-if="toggle" ng-click="add()">
      Add
    </button>

    <button ng-if="!toggle" ng-click="subtract()">
      Subtract
    </button>
  </div>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.