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

Stephanie Caldwell picture Stephanie Caldwell · Jul 9, 2013 · Viewed 41.2k times · Source

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.

Answer

Michelle Tilley picture Michelle Tilley · Jul 9, 2013

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