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

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

问题描述

我的控制器中有一个如下所示的函数:

AngularJS:

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

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

stuff

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

但是 myClass 没有被传递给 angular 函数.我怎样才能让它工作?如果我这样写,上面的代码就可以工作:

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

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

解决方案

在函数中

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

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

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

请注意,这不是特定于 Angular 的;这就是 JavaScript 的工作原理.以下面的例子:

>var obj = { a: 1, b: 2 }>var a = 'b'>对象1>obj[a]//同说:obj['b']2

<小时>

还有代码

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

假设您的作用域中有一个变量,例如$scope.myClass 计算结果为具有您要访问的属性名称的字符串.如果你字面上想传入字符串myClass,你需要

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

这个例子并没有让你很清楚你在寻找哪个(因为在顶部 div 上有一个名为 myClass 的类).

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

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>

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

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

解决方案

In the function

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

$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];
}

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>

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>

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天全站免登陆