jqueryangularjsui-select2

how to handle " The select2('destroy') method was called on an element that is not using Select2"


I am using ui-select2 and trying to open new page on click of edit button. I am seeing some strange issue. First time when I am opening the new page it is opening fine, but when I am cancelling it and again opening the same page, by clicking edit, it is giving me following error:

select2.full.min.js:3 The select2('destroy') method was called on an element that is not using Select2
angular.js:13708 TypeError: Cannot read property 'destroy' of undefined
at n.a.fn.select2 (select2.full.min.js:3)
at HTMLSelectElement.<anonymous> (select2.js:175)
at HTMLSelectElement.dispatch (jQuery-2.1.4.min.js:3)
at HTMLSelectElement.r.handle (jQuery-2.1.4.min.js:3)
at Object.trigger (jQuery-2.1.4.min.js:3)
at n.triggerHandler (jQuery-2.1.4.min.js:3)
at Function.pa.fn.on.pa.cleanData (angular.js:1865)
at n.remove (jQuery-2.1.4.min.js:3)
at angular.js:5504
at Object.push (angular.js:5085)

By reading this msg, it seems I will have to define destroy method but I am not getting how to define destroy method in my controller and how to call on cancel button (cancel method) call.. Following are the code snippet for select:

<select ui-select2 class="form-control input-lg" ng-model="cityId" ng-change="loadLocality()">
                                <option ng-repeat="city in cities|orderBy:'name'|filter:'ACTIVE':true" value="{{city.id}}">{{city.name}}</option>
                            </select>

Solution

  • Use a simple check for select2 like this:

    if ($('select').data('select2')) {
       $('select').select2('destroy');
     }
    

    I found the code in a GitHub Issue https://github.com/aldeed/meteor-autoform-select2/issues/44