Angular Chosen - a.forEach is not a function

12,921

The properties of the array objects should be assigned like this: id:"1", name:"United States", instead of id="1". Replace the equal sign (=) with colon (:).

Also you should use forEach function in the following way:

angular.forEach($scope.countries, function(key, value){
// your code here
 });

and not as a function of the array: $scope.countries.forEach(...)

Share:
12,921
user2085143
Author by

user2085143

Updated on June 11, 2022

Comments

  • user2085143
    user2085143 almost 2 years

    Using Angular Chosen to allow a multi select drop down for nationalities. https://github.com/localytics/angular-chosen

    I am getting an error of

    "a.forEach is not a function"

    This error occurs whether you have selected one, two or zero options.

    I have looked at this post

    Getting a a.foreach is not a function error

    however my selected value is already an array so it does not provide any help on the issue.

    Here is my html

    <li class="form-row">
                    <span class="label">
                        <label for="nation">Nationality</label>:
                    </span>
                    <div class="field country">
                        <select 
                        chosen
                        multiple
                        ng-model='person.nation'
                        ng-options='c.name as c.name for c in countries'
                        id="nation" 
                        data-select-max="2" 
                        data-token="Nationalities" 
                        data-placeholder="- Select your nationalities -">
                        </select>
                    </div>
                </li>
    

    And my options ($scope.countries) looks like

    [ 
      { id="1",  name="United States"}, 
      { id="2185",  name="Afghanistan"},
      etc....
     ]
    

    Any advice would be much appreciated.

  • user2085143
    user2085143 over 8 years
    You are correct, however changing it so does not remove the forEach error!
  • Ivan Eftimov
    Ivan Eftimov over 8 years
    I think in your code you are invoking forEach as it is a function of the array itself. The correct use is angular.forEach($scope.countries, function(key, value){ // your code here }); See angular documentation for more details
  • user2085143
    user2085143 over 8 years
    The forEach function is being called from the chosen library, not as part of my own implementation. It is called using "angular.forEach". The library can be viewed in the first link of my post.
  • Ivan Eftimov
    Ivan Eftimov over 8 years
    Can you share the whole code and markup, cause I cannot reproduce your issue in any other way then the one I mentioned above.