Search code examples
javascriptangularjsselectmultiple-select

Angularjs Multiple Select: Cannot read property 'length' of undefined


I have tried many variations but nothing seem to work.

I am getting the following error:

TypeError: Cannot read property 'length' of undefined
at select.js:1560
at m.$broadcast (angular.js:18487)
at Object.ctrl.select (select.js:673)
at fn (eval at compile (angular.js:15358), <anonymous>:4:453)
at e (angular.js:26994)
at b.$eval (angular.js:18161)
at b.$apply (angular.js:18261)
at HTMLDivElement.<anonymous> (angular.js:26999)
at HTMLDivElement.dispatch (jquery-3.2.1.min.js:3)
at HTMLDivElement.q.handle (jquery-3.2.1.min.js:3)

My code in the HTML part is:

<label for="addRecipient" class="bold">Additional Recipients:</label>
<ui-select multiple ng-model="addRecipient.selection" theme="bootstrap" title="Choose Recipients" class="multipleSelect">
<ui-select-match placeholder="Select Additional Recipients...">{{$item.name}}</ui-select-match>
<ui-select-choices repeat="additional in addRecipients | filter:$select.search">
 {{additional.name}}
</ui-select-choices>
</ui-select>

And in my controller:

$scope.addRecipient = {}; 
$scope.addRecipients =  [];
$.each(success.data.d.results, function (ind, val) {
  $scope.addRecipients.push({'name': val.Title, 'email':val.Email});
}); 

I can see the options to select in my select, however every time I click in any option, I get that error. Here is the dropdown showing the info from success.data.d.results:

dropdown


Solution

  • This is how my code looks now and it is working. Thank you @NTP for the hint!

    <label for="addRecipient" class="bold">Additional Recipients:</label>
    <ui-select multiple ng-model="addRecipient.selected" theme="bootstrap" title="Choose Recipients" class="multipleSelect">
       <ui-select-match placeholder="Select Additional Recipients...">{{$item.Title}}</ui-select-match>
       <ui-select-choices repeat="additional in addRecipients | filter:$select.search">
           {{additional.Title}}
    </ui-select-choices>
    

    In the controller:

    $scope.addRecipient = {}; 
    $scope.addRecipients = [];
    

    Dropdown values:

    $scope.addRecipients = success.data.d.results;
    

    Getting selected values:

    //add Recipient
    var addRecipients;
    if ($scope.addRecipient.selected && $scope.addRecipient.selected !='undefined'){
         things = [];
         console.log($scope.addRecipient.selected);
         for (var key in $scope.addRecipient.selected) {
              if (key < $scope.addRecipient.selected.length) {
                     things.push($scope.addRecipient.selected[key].Email) ;
              }
          }
          addRecipients = things;
     }