schumacherj
schumacherj

Reputation: 1324

Angularjs ng-class not working as expected

I have a angularjs app and I am trying to use the angularjs ng-class operator to toggle between two classes. I have tried using the ternary operator and have moved back to do it the old way. Below is my code:

<span ng-class="{'expand':boolExpander,'undoExpand':!boolExpander, }" ng-init="boolExpander=false" ng-click="boolExpander=!boolExpander"></span>

The span tag is just a holder for an icon which is defined in the css as such:

.expand {
    background: url(../assets/icons/glyphicons/glyphicons/png/glyphicons_432_plus.png) no-repeat 6px center;
    width: 40px;
    height: 40px;
    display: block;
}

As you can imagine the undoExpand class selects a different icon, but is otherwise exactly the same.

Whenever the user clicks the first time, the angularjs app throws an Error, "undefined is not a function" and then after clicking a few more times, the entire span goes away.

So what is happening and why? It seems like this should be straightforward and just work.

Here is the entire Error that happens when the ng-Click is triggered:

TypeError: undefined is not a function
    at Object.h [as fn] (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js:140:281)
    at k.$digest (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js:109:403)
    at k.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js:112:398)
    at HTMLSpanElement.<anonymous> (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js:194:147)
    at HTMLSpanElement.m.event.dispatch (http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js:3:8436)
    at HTMLSpanElement.r.handle (http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js:3:5146) angular.js:10061(anonymous function) angular.js:10061(anonymous function) angular.js:7357k.$digest angular.js:12531k.$apply angular.js:12777(anonymous function) angular.js:19093m.event.dispatch jquery.min.js:3r.handle

Upvotes: 1

Views: 1822

Answers (3)

zs2020
zs2020

Reputation: 54541

The correct syntax is

ng-class="{true:'expand',false:'undoExpand'}[boolExpander]"

Upvotes: 0

Shibbir Ahmed
Shibbir Ahmed

Reputation: 1350

This should work:

<span ng-class="(boolExpander) ? 'expand' : 'undoExpand'" ng-init="boolExpander='false'" ng-click="boolExpander=!boolExpander"></span>

Upvotes: 2

Josep
Josep

Reputation: 13071

Try this:

<span ng-class="{'expand':boolExpander,'undoExpand':!boolExpander }" ng-init="boolExpander=false" ng-click="boolExpander=!boolExpander"></span>

The comma at the end of the ng-class was generating an error.

Working example

Upvotes: 2

Related Questions