How can I pass a parameter to an ng-click function?

倖福魔咒の 提交于 2019-12-08 15:00:29

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/17538910/how-can-i-pass-a-parameter-to-an-ng-click-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!