簡體   English   中英

AngularJS用函數更改類

[英]AngularJS changing class with function

我有一個Agular應用程序,其中有一個美國州列表以“塊”方式布置為UL。

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

現在,當狀態變量具有條目時,特定狀態的類應處於活動狀態(以栗色顯示)。 我正在使用函數設置類,因為您不能使用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>
$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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM