2014-07-01 63 views
0

我已經有這個foreach設置狀態的選定值在statesList正確的_searchParam[key] == state.id
但是,如果_searchParam[key]包含此格式」,‘NH,TX’不止一個值,那麼,如果語句失敗,從來沒有發生的比賽,因此所有的項目都被選擇設置爲false。AngularJS對於每個問題

var _states = []; 
angular.forEach($scope.statesList, function (state, key2) { 
    if(_searchParams[key].indexOf(state.id) > -1) 
     if(state.id == _searchParams[key]) { 
     state.selected = true; 
    } else { 
     state.selected = false;   
    } 
    this.push(state); 
    if(state.selected) 
     $scope.states.push(state); 
}, _states); 

所以,我試圖分裂通過他們的_searchParams[key]值和循環,但它不工作。看到錯誤的評論

var _states = []; 
angular.forEach($scope.statesList, function (state, key2) { 
    if(_searchParams[key].indexOf(state.id) > -1) 
     var sp = _searchParams[key].split(','); 
     for(i = 0; i < sp.length; i++) { 
      if(state.id == sp[i]) { 
       state.selected = true; 
      } else { 
       state.selected = false;   
      } 
     } 
    } 
    this.push(state); // get unexpected token this 
    if(state.selected) 
     $scope.states.push(state); 
}, _states); 

所以,我感動this.push(state)行成,如果(在那裏真的應該是這樣),並且得到錯誤

var _states = []; 
angular.forEach($scope.statesList, function (state, key2) { 
    if(_searchParams[key].indexOf(state.id) > -1) 
     var sp = _searchParams[key].split(','); 
     for(i = 0; i < sp.length; i++) { 
      if(state.id == sp[i]) { 
       state.selected = true; 
      } else { 
       state.selected = false;   
      } 
     } 
     this.push(state); 
    } 
    if(state.selected) // get unexpected token if 
     $scope.states.push(state); 
}, _states); 

現在我該如何解決這個問題,因爲我不確定這個forEach()會發生什麼情況會導致這些錯誤? 的statesList的定義是這樣的:

$scope.statesList = [ 
    { "id": "AK", "name": "Alaska", "selected": false}, 
    { "id": "AL", "name": "Alabama", "selected": false}, 
    // SNIPPED most of states 
    { "id": "WY", "name": "Wyoming", "selected": false}, 
    { "id": "DC", "name": "District of Columbia", "selected": false}, 
    { "id": "MX", "name": "Mexico", "selected": false}]; 

回答

1

看來,你是缺少一個左括號柯利{。添加它,像這樣:

if(_searchParams[key].indexOf(state.id) > -1) { 

然後取出您添加的拆分部分。否則,在某些情況下,您會將state.selected設置爲true,然後設置爲false。

+0

做了這項工作,如何忽略這些事情會讓你陷入困境,以及有時你無法看到最小的事情,這真是太神奇了。謝謝。我實際上修改了它一點,以正確處理所選值的設置。 – MB34