1

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.

3 Answers 3

7

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);
 });
Sign up to request clarification or add additional context in comments.

1 Comment

"Turning into a String" approach won't work , error : Error: [$compile:nodomevents] Interpolations for HTML DOM event attributes are disallowed. Please use the ng- versions (such as ng-click instead of onclick) instead. However, moving it into the controller did +1!
4

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>

Comments

0

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

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

2 Comments

I'm not passing it back to an Angular controller. Ng-click wouldn't work.
I think I misunderstood you as you were trying to tell me to move everything into the controller by using ng-click. I was not aware that this is what you meant, so +1.

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.