How do I compare with a string in ng-class?

2019-05-04 09:18发布

问题:

This line doesn't seem to work for me.

Sort By: <a href="" ng-click="setOrder('title')" ng-class="{active: orderProp == 'title'}">Alphabetical</a>

Do I have to escape 'title' in orderProp == 'title' somehow?

in the controller I have

...
$scope.orderProp = 'title';
$scope.setOrder = function(sortBy){
            $scope.orderProp = sortBy;
}
...

Thank you

Update: Using v1.3.0-beta.17

Adding ng-class="{active:orderProp=='pagetitle'} to

<a href="" ng-click="setOrder('pagetitle')" ng-class="{active:orderProp=='pagetitle'}">Alphabetical</a>

throws an error

"Error: [$parse:syntax] http://errors.angularjs.org/1.3.0-beta.17/$parse/syntax?p0=undefined&p1=not%20a%20primary%20expression&p2=null&p3=%7Bactive%3AorderProp%3D%3D&p4=%7Bactive%3AorderProp%3D%3D

Sorry for the way I present the error but I just started angular last week and don't know a better way

Update 2: error seems to be coming from = == ===. I tried > and no error occured. Is there an alternative syntax to like eq?

Update 3 with solve

I mapped each string to an int pagetile->1 code->2 + data-ng-class="{active:orderPropIdx==1};" Inside the controller I just do if pagetitle set active:orderPropIdx to 1 and so on

Maybe this is a bug in angular 1.3

回答1:

As is stated in the comments, your class name should be surrounded by single quotes.

ng-class="{'active': orderProp == 'title'}">

This comparison is case sensitive.



回答2:

Had the same issue when using ng-class. It refused to dynamically compute the class attribute even though the expression was successfully calculated.

And here is the workaround I've used for the ng-class statement:

Sort By: <a href="" ng-click="setOrder('title')" class="{{orderProp == 'title' ? 'active' : ''}}">Alphabetical</a>

instead of ng-class="{active: orderProp == 'title'} I've switched to class="{{orderProp == 'title' ? 'active' : ''}}"



回答3:

I mapped each string to an int pagetile->1 code->2 + data-ng-class="{active:orderPropIdx==1};" Inside the controller I just do if pagetitle set active:orderPropIdx to 1 and so on

Maybe this is a bug in angular 1.3



回答4:

I resolve in this way; 'ClassName':'{{Value}}'=='StringtoCompare', ...

ng-class="{ 'btn-danger' : '{{datasource.difficoltaRicetta}}'=='Difficile', 'btn-warning' :'{{datasource.difficoltaRicetta}}'=='Intermedia', 'btn-success' : '{{datasource.difficoltaRicetta}}'=='Facile'}"


回答5:

The syntax for ng-class can be quite confusing sometimes. Try this.

ng-class="{true: 'active', false: ''}[orderProp === 'title']"

Include square brackets after the curly braces. Inside the square brackets, you can declare any expression, and declare your results (true/false) and the corresponding classes you want to apply (active). And be sure to use '===' in your expressions, signifying you want orderProp to be exactly equal to what you are comparing it against.