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

1

13

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.

Christcross answered 9/7, 2013 at 2:20 Comment(1)
Seems myClass is a simple string, rather than a variable? In the expression toggleClass(myClass), myClass should be a variable on scope, or pass it as string 'myClass'Ajit
E
26

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

Eastnortheast answered 9/7, 2013 at 3:2 Comment(3)
This is the best answer to a question that I have ever seen on this site (and there are a lot of great answers). Very clear, very concise. Thanks so much!Christcross
Happy to have helped! As I've been mentioning recently, feel free to ping me if you have additional questions.Eastnortheast
Isn't class a reserved keyword in javascript ? I'm pretty sure that would break in IE.Extent

© 2022 - 2024 — McMap. All rights reserved.