简体   繁体   中英

change the text of the button on click using angular JS

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;
}

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>

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

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM