Javascript AngularJS使用函数更改类

Javascript AngularJS使用函数更改类,javascript,angularjs,Javascript,Angularjs,我有一个Agular应用程序,其中我有一个美国各州的列表,以UL的形式以“块”的方式进行布局 现在,当states变量有一个条目时,特定状态的类应该是活动的(以栗色显示)。我正在使用函数设置类,因为您无法在子句中使用。该代码确实进入函数,当状态=='TX'时,它确实返回true,但是,该类没有被应用 模板: <div ng-controller="MyCtrl" id="state_scroller"> <section class="states">

我有一个Agular应用程序,其中我有一个美国各州的列表,以UL的形式以“块”的方式进行布局

现在,当states变量有一个条目时,特定状态的类应该是活动的(以栗色显示)。我正在使用函数设置类,因为您无法在子句中使用
。该代码确实进入函数,当状态=='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>

  • {{state.id}
我做错了什么? 以下是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>

  • AK
  • TN
  • TX
  • UT
你必须检查所有的东西,如果找到了就回来。现在,如果第一个不匹配,则退出foreach。然后不从selectedState函数返回(foreach有自己的函数,返回selectedState函数,然后它什么也不返回)


我不认为angular
forEach
实现像其他库一样有提前终止。谢谢你。也许他们应该添加一个
break
子句?
$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;
};