Don Thomas Boyle
Don Thomas Boyle

Reputation: 3045

How to pass AngularJS ng-repeat Variable to Javascript click event

I would like to know how to pass Angular ng-repeat variable to my Javascript onclick event

My angular repeater

       <div class="data" data-ng-repeat="sub in subs" >  
            <button onclick="ConfirmDialog(sub.SubID)">Cancel</button>
            {{ sub.someOtherProperty}}
            {{ sub.someOtherProperty}}
            {{ sub.someOtherProperty}}                
        </div>

My script function

<script type='text/javascript'>

    function ConfirmDialog(subID) {
             console.log('Succesfully submitted id: ', subID);
    });
 </script>

The error : sub is not defined (in the onclick() call from the button element) all other properties show as expected.

Upvotes: 1

Views: 10785

Answers (3)

Mouneer
Mouneer

Reputation: 13489

If you don't want to use ng-click, you still have a chance! Try the following

<tr ng-repeat="supplier in suppliers" id="{{supplier.id}}">
       <button onclick="readVariable(this);">
</tr>

<script>
    function readVariable(elem){
        id = elem.parentNode.id;
        console.log(id);  //it works!
    }
</script>

Upvotes: 4

Brian Noah
Brian Noah

Reputation: 2972

You are running straight javascript onclick instead of ng-click.

move confirmDialog into your controller and ng-click can attach to it.

 <div class="data" data-ng-repeat="sub in subs" >  
        <button ng-click="ConfirmDialog(sub.SubID)">Cancel</button>            
 </div>

 $scope.ConfirmDialog = function (subID) {
         console.log('Succesfully submitted id: ', subID);
 });

Upvotes: 7

D_R
D_R

Reputation: 4962

You should use ng-click instead in order to access the ng-repeat variable

<button ng-click="ConfirmDialog(sub.SubID)">Cancel</button>

Upvotes: 0

Related Questions