如何将 AngularJS ng-repeat 变量传递给 Javascript 点击事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26790374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:29:38  来源:igfitidea点击:

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

javascriptangularjsparameter-passingng-repeat

提问by Don Thomas Boyle

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

我想知道如何将 Angular ng-repeat 变量传递给我的 Javascript onclick 事件

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.

错误 : sub 未定义(在来自按钮元素的 onclick() 调用中)所有其他属性均按预期显示。

回答by Brian Noah

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

您正在直接运行 javascript onclick 而不是 ng-click。

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

将 confirmDialog 移动到您的控制器中,然后 ng-click 可以附加到它。

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

回答by Mouneer

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

如果你不想使用 ng-click,你还有机会!尝试以下

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

回答by D_R

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

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

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