如何将参数传递给ng-click函数? [英] How can I pass a parameter to an ng-click function?

查看:156
本文介绍了如何将参数传递给ng-click函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器中有一个类似于以下内容的函数:

I have a function in my controller that looks like the following:

AngularJS:

AngularJS:

$scope.toggleClass = function(class){
    $scope.class = !$scope.class;
}

我希望通过传递要切换的类的名称来保持通用性:

I want to keep it general by passing the name of the class that I want to toggle:

<div class="myClass">stuff</div>
<div ng-click="toggleClass(myClass)"></div>

但是myClass没有传递给角度函数.我怎样才能使它正常工作?如果我这样写,上面的代码将起作用:

But myClass is not being passed to the angular function. How can I get this to work? The above code works if I write it like this:

$scope.toggleClass = function(){
    $scope.myClass = !$scope.myClass;
}

但是,这显然不是一般性的.我不想在名为myClass的类中进行硬编码.

But, this is obviously not general. I don't want to hard-code in the class named myClass.

推荐答案

在函数中

$scope.toggleClass = function(class){
    $scope.class = !$scope.class;
}

$scope.class与参数class没有任何关系.它实际上是$scope上的一个称为class的属性.如果要访问变量class标识的$scope$scope的属性,则需要使用数组式访问器:

$scope.class doesn't have anything to do with the paramter class. It's literally a property on $scope called class. If you want to access the property on $scope that is identified by the variable class, you'll need to use the array-style accessor:

$scope.toggleClass = function(class){
    $scope[class] = !$scope[class];
}

请注意,这不是特定于Angular的;这就是JavaScript的工作方式.请看以下示例:

Note that this is not Angular specific; this is just how JavaScript works. Take the following example:

> var obj = { a: 1, b: 2 }
> var a = 'b'
> obj.a
  1
> obj[a] // the same as saying: obj['b']
  2


还有代码


Also, the code

<div ng-click="toggleClass(myClass)"></div>

假设您的范围内有一个变量,例如$scope.myClass的结果为字符串,该字符串具有您要访问的属性的名称.如果您从字面上看要传递字符串myClass,则需要

makes the assumption that there is a variable on your scope, e.g. $scope.myClass that evaluates to a string that has the name of the property you want to access. If you literally want to pass in the string myClass, you'd need

<div ng-click="toggleClass('myClass')"></div>

该示例并不能使您非常清楚所要查找的内容(因为顶部div上有一个名为myClass的类).

The example doesn't make it super clear which you're looking for (since there is a class named myClass on the top div).

这篇关于如何将参数传递给ng-click函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆