2014-06-30 30 views
0

我有一个Agular应用程序,我有一个美国国家列表布局作为一个“块”时尚UL。AngularJS改变职能与功能

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

现在,当状态变量具有一个条目,在特定状态下的类应该是主动的(在栗色示出)。我正在使用函数设置类,因为您不能使用in子句。代码DOES进入函数,当状态=='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
$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/

+0

我不相信angular'forEach'实现像其他库一样提前终止。 –

+0

感谢那个。也许他们应该添加一个'break'子句? – MB34