Bad syntax of expression in ng-class?
-
21-12-2019 - |
Question
I am learning Angular.js and I have this piece of code:
<button ng-class="{'btn pull-left',
duplicatesInList === true ? 'btn-warning': 'btn-success'}"
id="saveScoreButton" type="button" ng-click="add()"><button>
And something is wrong with syntax but I have no idea what... What I want to do is find duplicates in list, and when there is a duplicate I want to warn user by change save button style (class btn-warning). I will be very happy in anybody decides to help me, thank you in advance. Update: Console log:
Error: [$parse:syntax] http://errors.angularjs.org/1.2.16/$parse/syntax?p0=%2C&p1=is%20unexpected%2C%20expecting%20%5B%3A%5D&p2=17&p3=%7B'btn%20pull-left'%2CNaNuplicatesInList%20%3D%3D%3D%20true%20%3F%20'btn-warning'%3A%20'btn-success'%7D&p4=%2C%duplicatesInList%20%3D%3D%3D%20true%20%3F%20'btn-warning'%3A%20'btn-success'%7D
Pretty weird for me. SOLUTION:
ng-class="duplicatesInList === true?
'btn btn-warning pull-left': 'btn btn-success pull-left'"
Codes in answers also works (and IMO are a little better wrote than my solution:) )
Solution
<button ng-class="{
'btn pull-left' : true,
'btn-warning' : duplicatesInList,
'btn-success' : !duplicatesInList
}"
id="saveScoreButton" type="button" ng-click="add()"><button>
OTHER TIPS
An alternative solution is,
<button class="btn pull-left"
ng-class="duplicatesInList ? 'btn-warning': 'btn-success'"
id="saveScoreButton" type="button" ng-click="add()"></button>
Here's a working example:
Html:
<div ng-app='myApp' ng-controller='testCtrl'>
<button ng-class="{
'btn-pull-left' : true,
'btn-warning' : duplicatesInList,
'btn-success' : !duplicatesInList
}" id="saveScoreButton" type="button" ng-click="add()">Here</button>
</div>
CSS:
.btn-pull-left
{
float:left;
}
.btn-warning
{
color:blue;
}
.btn-success
{
color: green;
}
JS:
angular.module('myApp',[]).
controller('testCtrl',function ($scope){
$scope.add = function(){
$scope.duplicatesInList = !$scope.duplicatesInList;
}
});
And the most important -> FIDDLE.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow