Reputation: 1114
How I can change the text of the button on click of the button.
Here it is what I have tried.
HTML:
<button ng-click="toggle = !toggle">Toggle!</button>
<div class="box on" ng-show="toggle" ng-animate="'box'">On</div>
JS:
function MainController($scope) {
$scope.toggle = true;
}
Upvotes: 19
Views: 50106
Reputation: 57384
Existing answers are good, but here's a somewhat more refined solution using a ternary to select the appropriate text depending on whether the toggle is on or off. Additionally, toggle
is a somewhat unclear variable name since it's not clear what states "true" or "false" correspond to. Perhaps toggleOn
or simply on
is better.
angular.module("exampleApp", [])
.controller("toggleCtrl", function($scope) {
$scope.on = true;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.js"></script>
<div ng-app="exampleApp" ng-controller="toggleCtrl">
<button ng-click="on = !on">
Toggle {{on ? "off" : "on"}}
</button>
<div ng-show="on">On</div>
</div>
Upvotes: 0
Reputation: 1405
Or, keep all the content in your HTML, rather than defining the button text in the controller, if you prefer:
<button ng-click="toggle = !toggle">
<span ng-show="toggle">Toggle to Off</span>
<span ng-hide="toggle">Toggle to On</span>
</button>
<div class="box on" ng-show="toggle" ng-animate="'box'">On</div>
Upvotes: 29
Reputation: 896
Here's my solution, supporting translation:
HTML:
<span class="togglebutton">
<label>
<input type="checkbox" checked="{{myApp.enabled}}"
ng-model="myApp.enabled" ng-click="toggleEnabled()">
<span translate="{{myApp.enableCaption}}">Is Enabled?</span>
</label>
</span>
JS - Controller:
$scope.toggleEnabled = function() {
$scope.myApp.enableCaption = $scope.myApp.enabled ? 'global.enabled' : 'global.disabled';
};
where global.enabled
and global.disabled
refer to i18n JSON translations. You also need to initialize enableCaption
in JS, in place where you create an empty object.
Upvotes: 0
Reputation: 7225
I would use neither watch nor ng-show because of their performance. That is simple as this:
app.controller('AppController', function ($scope) {
$scope.toggle = true;
})
<button ng-click="toggle = !toggle">{{toggle && 'Toggle!' || 'some text'}}</button>
Upvotes: 9
Reputation: 388436
I think, using a watch of toggle
should do it
<button ng-click="toggle = !toggle">{{toggleText}}</button>
<div class="box on" ng-show="toggle" ng-animate="'box'">On</div>
then
app.controller('AppController', function ($scope) {
$scope.toggle = true;
$scope.$watch('toggle', function(){
$scope.toggleText = $scope.toggle ? 'Toggle!' : 'some text';
})
})
Demo: Fiddle
Upvotes: 22