如何将参数传递给ng-click函数? [英] How can I pass a parameter to an ng-click function?
问题描述
我的控制器中有一个类似于以下内容的函数:
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屋!