Angular changing button text on click

Niraj  picture Niraj · Dec 8, 2018 · Viewed 8.6k times · Source

I am working on a game where I need to let the user choose the next level upon completion of the previous level. This can go on up to level 7.

I need to be able to change the text on the button to indicate the next label number up to 7.

So, in the controller, I need to read the button text displayed previously so that I can display the next number.

Could someone please help? Here is my codepen codepen link

and the accompanying code that I have tried so far

<html ng-app="myApp">
  <body ng-controller="myCtrl">
     <div id="nextlevel">
        <h3>Level Completed!</h3>
        <button id="nextplay" ng-model="number" ng-init="buttontext='Level 
        2'">{{buttontext}}</button>
   </div>    
  </body>
</html>

and the controller -

myApp = angular.module("myApp",[]);

myApp.controller("myCtrl", function($scope){

  document.getElementById("nextplay").addEventListener('click', function() {
        nextlevel.style.display = 'none';
        setTimeout(function() {
          nextlevel.style.display = '';
        }, 500);

        if ($scope.number <=7) {            
           $scope.number = $scope.number + 1;
        }
        el.emit('gameStarted', {});        
    });
  $scope.buttontext = "Level " + $scope.number;
});

I am not sure how to update the value of the button text to next value.

Answer

amir.algazi picture amir.algazi · Dec 8, 2018

Here is a solution and some notes that I recommend to pay attention on:

 <html ng-app="myApp">
  <body ng-controller="myCtrl">
   <div id="nextlevel">
     <h3>Level Completed!</h3>
     <button id="nextplay" ng-click="buttonClicked()">
      Level {{number}}
     </button>
   </div>
  </body>
 </html>


  myApp = angular.module("myApp",[]);

  myApp.controller("myCtrl", function($scope) {
  $scope.number = 1;

  $scope.buttonClicked = function() {
    nextlevel.style.display = 'none';
    setTimeout(function() {
      nextlevel.style.display = '';
    }, 500);
    $scope.number++;
  }
 });
  • Instead of 'addEventListener', in AngularJs there is a directive called 'ng-click' which invokes functions that are included in the controller's $scope.

  • Level can be written directly in your html with binding to a variable of $scope (called 'number').

  • The directive 'ng-init' is not needed here.