ng-class中表达式的错误语法?

时间:2014-06-04 19:16:25

标签: javascript angularjs twitter-bootstrap button ng-class

我正在学习Angular.js,我有这段代码:

<button ng-class="{'btn pull-left', 
duplicatesInList === true ? 'btn-warning': 'btn-success'}" 
id="saveScoreButton" type="button" ng-click="add()"><button>

语法有问题,但我不知道是什么......我想做的是在列表中找到重复项,当有重复时我想通过更改保存按钮样式警告用户(类btn-warning )。我会很高兴任何人决定帮助我,提前谢谢你。 更新:控制台日志:

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

对我来说很奇怪。 的

ng-class="duplicatesInList === true? 
'btn btn-warning pull-left': 'btn btn-success pull-left'"

答案中的代码也有效(并且IMO比我的解决方案写的好一点:))

3 个答案:

答案 0 :(得分:3)

<button ng-class="{
    'btn pull-left' : true,
    'btn-warning' : duplicatesInList,
    'btn-success' : !duplicatesInList
    }"
id="saveScoreButton" type="button" ng-click="add()"><button>

答案 1 :(得分:1)

另一种解决方案是,

<button class="btn pull-left" 
ng-class="duplicatesInList ? 'btn-warning': 'btn-success'"
id="saveScoreButton" type="button" ng-click="add()"></button>

答案 2 :(得分:0)

这是一个有效的例子:

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;
    }
});

最重要的 - &gt; FIDDLE