javascriptangularjsangular-chosen

Getting error while including AngularJS multiple chosen directive


I'm getting the following error while implementing the AngularJS chosen directive.

Error: TypeError: a.map is not a function at nh.q.writeValue (angularjslatest.js:307) at Object.e.$render (angularjslatest.js:328) at angularjslatest.js:310 at angularjslatest.js:146 at m.$digest (angularjslatest.js:147) at m.$apply (angularjslatest.js:150) at l (angularjslatest.js:102) at XMLHttpRequest.s.onload (angularjslatest.js:108)

I'm explaining my code below:

<select chosen 
        multiple 
        class="form-control oditek-form" 
        name="category" 
        id="category" 
        ng-model="category" 
        ng-options="s.value as s.name for s in listOfCategory">
</select>

My controller code is given below.

$scope.listOfCategory = [{
  name: 'Select Category',
  value: ''
}];

$scope.category = $scope.listOfCategory[0];

var fileURL = '';
var url1 = '../service/admin/vechile/service/service.php?action=getAllCategoryData';
var method = 'GET';
var data1 = '';

DataService.connectToServerSideScript(method, url1, data1).then(function(response) {
  if (response.length > 0) {
    angular.forEach(response, function(obj) {
      var cdata = {
        'name': obj.category_name,
        'value': obj.id
      };
      $scope.listOfCategory.push(cdata);
    })
  }
}, function(error) {

});

Here I'm getting all the data but those error is coming in browser console. Here I need to clear those error.


Solution

  • You need to setup your selected model as an array:

    $scope.category = angular.isDefined($scope.listOfCategory[0]) ? 
                          [$scope.listOfCategory[0]] : [];
    

    Please note that this also fixes the following error message:

    Error: TypeError: a.forEach is not a function