首页 > 解决方案 > 单击时更改按钮文本的角度

问题描述

我正在开发一个游戏,我需要让用户在完成上一个级别后选择下一个级别。这可以持续到第 7 级。

我需要能够更改按钮上的文本以指示下一个标签编号最多为 7。

因此,在控制器中,我需要读取之前显示的按钮文本,以便显示下一个数字。

有人可以帮忙吗?这是我的codepen codepen链接

以及到目前为止我尝试过的随附代码

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

和控制器 -

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

我不确定如何将按钮文本的值更新为下一个值。

标签: angularjsangular-ngmodelng-bind

解决方案


这是一个解决方案和一些我建议注意的注意事项:

 <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++;
  }
 });
  • 在 AngularJs 中有一个名为“ng-click”的指令,而不是“addEventListener”,它调用包含在控制器的 $scope 中的函数。

  • 级别可以直接在您的 html 中编写,并绑定到 $scope 的变量(称为“数字”)。

  • 这里不需要指令“ng-init”。


推荐阅读