AngularJS 1,传递按钮值

时间:2017-02-24 13:13:06

标签: angularjs

可能是一个非常简单的问题,但我似乎无法找到有效的答案。我试图通过点击功能{{data}}来点击按钮内的revealNumbers

<button class="select" ng-click="revealNumbers(firstNumber)">{{firstNumber}}</button>
<button class="select" ng-click="revealNumbers(secondNumber)">{{secondNumber}}</button>

控制器:

            $scope.revealNumbers = function(num) {

                $scope.result = num
                console.log($scope.result)

        var randomInteger = (getRandomInt(1, 2))
if (randomInteger==2) {
            $scope.firstNumber = 5
            $scope.secondNumber = 10
        } else if ( randomInteger ==1) {
            $scope.firstNumber = 3
            $scope.secondNumber = 8
        }
        }

我在控制台中得到undefined。任何帮助非常感谢。谢谢!

2 个答案:

答案 0 :(得分:1)

值的声明应该在回调函数之外,所以得到这两行:

//if in start command "--continue" was added, then apply ignoring for android test fails
gradle.taskGraph.whenReady { graph ->
    if (gradle.startParameter.continueOnFailure) {
        graph.allTasks.findAll { it.name ==~ /connected.*AndroidTest/ }*.ignoreFailures = true
    }
}
在您的$scope.secondNumber = 5 $scope.firstNumber = 10 声明之前

您的当前实现在按钮单击后(在单击事件回调中)初始化这些变量,因此第一次单击将给出错误,因为变量未定义,下一个将起作用。

答案 1 :(得分:0)

您可以向您的处理程序传递angularJS $事件obejct并从此$ event对象引用元素innerText。

所以你的代码应如下所示:

angular.module('newModule', []).controller('myCtrl', function($scope){
  $scope.firstName = "Jenkins";
  $scope.lastName = "Lincoln";
  
  $scope.revealNumbers = function(event){
    console.log(event.target.innerText);
  }
  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


<div ng-app="newModule" ng-controller="myCtrl" >
  <button class="select" ng-click="revealNumbers($event)">{{firstName}}</button>
  <button class="select" ng-click="revealNumbers($event)">{{lastName}}</button>
</div>