0

Probably a very simple question, but I can't seem to find an answer that works. I'm trying to pass the {{data}} inside a button on click through a function, revealNumbers.

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

Controller:

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

I get undefined in the console. Any help greatly appreciated. Thank you!

7
  • firstNumber and secondNumber should be properties on the $scope. If they are undefined on the scope so will the passed in parameter value be undefined. Commented Feb 24, 2017 at 13:14
  • Please show how you set a value of firstNumber and secondNumber. Commented Feb 24, 2017 at 13:15
  • Sorry, edited now. Commented Feb 24, 2017 at 13:15
  • Also wrong, you should set the values of secondNumber and firstNumber outside of your method. Like in the controller's or directive's constructor for example. Commented Feb 24, 2017 at 13:16
  • Oh okay, maybe that's the issue. Commented Feb 24, 2017 at 13:18

2 Answers 2

1

Declaration of values should be outside callback function, so get those two lines:

$scope.secondNumber = 5
$scope.firstNumber = 10

before Your $scope.revealNumbers declaration.

Your current implementation initialize those variables after button click ( in click event callback ), so the first click will give error because variables are undefined, next ones will work.

Sign up to request clarification or add additional context in comments.

1 Comment

That was it. Thank you!
0

You can pass to your handler an angularJS $event obejct and reference the element innerText from this $event object.

So your code should look as follows:

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.