2014-06-30 37 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