MB34
MB34

Reputation: 4404

AngularJS forEach issue

I already have this foreach that sets the selected value for the state in statesList correctly for a _searchParam[key] that == the state.id.
However, if the _searchParam[key] contains more than one value in this format" "NH,TX" then the if statement fails and the match never occurs so all items get selected set to false.

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);

So, I tried to split the _searchParams[key] value and loop through them but it is not working. See error in comment

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);

So, I moved the this.push(state) line into the if (where it really should be anyway), and get the error below.

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);

Now how can I fix this as I'm not sure what is going on in this forEach() that would be causing these errors? The statesList is defined like this:

$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}];

Upvotes: 0

Views: 411

Answers (1)

user3141592
user3141592

Reputation: 1112

It appears that you are missing an opening curley brace {. Add it, like this:

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

And then take out the split part you added. Otherwise, in some cases you'd set state.selected to true then to false.

Upvotes: 1

Related Questions