I want to change a button name once it is clicked.There are two function 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 name of 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.
Asked
Active
Viewed 1,438 times
1 Answers
1
Try the following
Controller
export class AppComponent {
buttonNameToggle = true;
buttonName: 'Add' | 'Subtract' = 'Add';
onMouseUp() {
this.buttonName = this.buttonNameToggle ? 'Add' : 'Subtract';
}
}
Template
<button (mouseup)="buttonNameToggle = !buttonNameToggle; onMouseUp()">{{ buttonName }}</button>
Update: AngularJS
Controller
var module = angular.module("myModule", []);
module.controller("myController", function($scope) {
$scope.toggle = true;
});
Template
<div ng-app="myModule">
<div ng-controller="myController">
<button ng-click="toggle = !toggle">
{{ toggle ? 'Add' : 'Subtract' }}
</button>
</div>
</div>
Working example: JSFiddle
Update: call different event handlers
Controller
var module = angular.module("myModule", []);
module.controller("myController", function($scope) {
$scope.toggle = true;
$scope.add = () => { console.log('add called') };
$scope.subtract = () => { console.log('subtract called') };
});
Template
<div ng-app="myModule">
<div ng-controller="myController">
<button ng-click="toggle = !toggle; toggle ? subtract() : add()">
{{ toggle ? 'Add' : 'Subtract' }}
</button>
</div>
</div>
Add the event handlers based on the status of the toggle
variable. If toggle
is true call subtract()
, if not call add()
function.
Working example: JSFiddle
-
Thanks .It is angular js. But can we please share the java script code also for the same – Millie Jun 09 '20 at 07:40
-
AngularJS and Angular are very different versions. What I've shown is Angular. For pure Javascript, it has been already extensively documented. Eg. https://stackoverflow.com/q/10671174/6513921 – ruth Jun 09 '20 at 07:42
-
yes . I want in Angular js and javascript not in Angular. I did not understand export class Appcomponent which is in angular ,how we can convert this to angular js – Millie Jun 09 '20 at 07:51
-
thanks a lot!! @Michael D .Add and Subtract are function name , Right? – Millie Jun 09 '20 at 08:04
-
i can toggle the button add to subtract but facing issue with calling function add and subtract both. Please help – Millie Jun 09 '20 at 10:15
-
@VarshaAkhade: I've updated the answer to call different event handlers based on the value of `toggle` variable. – ruth Jun 12 '20 at 09:32