AngularJS用函数改变类

时间:2014-06-30 22:07:09

标签: javascript angularjs

我有一个Agular应用程序,我有一个美国州的列表,作为一个"块"方式。

http://jsfiddle.net/Mrbaseball34/3u375/

现在,当states变量有一个条目时,特定状态的类应该是活动的(以栗色显示)。我使用函数设置类,因为你不能使用in子句。代码进入函数,当状态==' TX'时,它返回true,但是,该类没有被应用。

模板:

<div ng-controller="MyCtrl" id="state_scroller">
    <section class="states">
        <ul>
            <li ng-repeat="state in statesList" 
                ng-class="{true: 'active', false: ''}[selectedState($index)]"  
                id="st_{{state.id}}">{{state.id}}</li>
        </ul>
    </section>
</div>

我在这里做错了什么? 以下是Chrome调试器中呈现的代码的外观:

<div ng-controller="MyCtrl" id="state_scroller" class="ng-scope">
    <section class="states">
        <ul>
            <!-- ngRepeat: state in statesList -->
            <li ng-repeat="state in statesList" 
                ng-class="{true: 'active', false: ''}[selectedState($index)]" 
                id="st_AK" class="ng-scope ng-binding">AK</li>
            <!-- end ngRepeat: state in statesList -->
   <!-- snipped some -->
            <li ng-repeat="state in statesList" 
                ng-class="{true: 'active', false: ''}[selectedState($index)]" 
                id="st_TN" class="ng-scope ng-binding">TN</li>
            <!-- end ngRepeat: state in statesList -->
            <li ng-repeat="state in statesList" 
                ng-class="{true: 'active', false: ''}[selectedState($index)]" 
                id="st_TX" class="ng-scope ng-binding">TX</li>
            <!-- end ngRepeat: state in statesList -->
            <li ng-repeat="state in statesList" 
                ng-class="{true: 'active', false: ''}[selectedState($index)]" 
                id="st_UT" class="ng-scope ng-binding">UT</li>
            <!-- end ngRepeat: state in statesList -->
   <!-- snipped rest -->
            <!-- end ngRepeat: state in statesList -->
        </ul>
    </section>
</div>

1 个答案:

答案 0 :(得分:1)

$scope.selectedState = function(id) {
    var x = false;
    angular.forEach($scope.states, function (state, key2) {
        if (state.id == $scope.statesList[id].id) {
            x = true;
        }
    })
    return x;
};

您必须检查所有内容,如果找到则返回。现在,如果第一个不匹配,则退出foreach。然后你不会从selectedState函数返回(foreach有它自己的函数,它返回到selectedState函数,然后它不返回任何东西。

http://jsfiddle.net/3u375/17/