Javascript 如何将绑定变量传递给 ng-click 函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12647891/
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-08-23 10:56:18  来源:igfitidea点击:

How can you pass a bound variable to an ng-click function?

javascriptangularjs

提问by ccraig

I have a simple delete button that will accept a string or number but won't accept an ng-model variable ( not sure if that's the correct terminology ).

我有一个简单的删除按钮,它可以接受字符串或数字,但不接受 ng-model 变量(不确定这是否是正确的术语)。

<button class="btn btn-danger" ng-click="delete('{{submission.id}}')">delete</button>

Which generates:

产生:

<button class="btn btn-danger" ng-click="delete('503a9742d6df30dd77000001')">delete</button>

However, nothing happens when I click. If I hard code a variable then it works just fine. I assume I'm just not doing things the "Angular" way, but I'm not sure what that way is :)

但是,单击时没有任何反应。如果我对变量进行硬编码,那么它就可以正常工作。我想我只是没有以“角度”的方式做事,但我不确定那种方式是什么:)

Here's my controller code:

这是我的控制器代码:

$scope.delete = function ( id ) {
    alert( 'delete ' + id );
}

回答by pkozlowski.opensource

You don't need to use curly brackets ({{}}) in the ng-click, try this:

您不需要在 中使用大括号 ( {{}}) ng-click,试试这个:

<button class="btn btn-danger" ng-click="delete(submission.id)">delete</button>

回答by Mistalis

The ngClickdirective binds an expression. It executes Angular code directly (as ngIf, ngChange, etc.) without the need of {{ }}.

ngClick指令绑定一个表达式。它直接执行角代码(如ngIfngChange等),而不需要的{{ }}

angular.module('app', []).controller('MyCtrl', function($scope) { 
    $scope.submission = { id: 100 };

    $scope.delete = function(id) {
        alert(id + " deleted!");
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="MyCtrl">
    <button ng-click="delete(submission.id)">Delete</button>
</div>