简体   繁体   中英

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.

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

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>

您应该改用ng-click来访问ng-repeat变量

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM