AngularJS ng-model binding on jquery-select2 (version 4.*) input field

488 Views Asked by At

I'm using jquery-select2 plugin on many places in my site. Now i need to add angularjs model binding to the existing form. The best solution that i found is angularjs wrapper ui-select2. But this wrapper does'n work with jquery-select2 version 4.* (it works with old version 3.*, but there is some bugs) Here is my Plunker

index.html

<!DOCTYPE html>
<html ng-app="MyApp">    
<head>    
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" />    
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.7/angular.min.js"></script>
  <script src="select2.js"></script>
  <script src="script.js"></script>
</head>

<body ng-controller="MyController">
  <h1>Select2</h1>

  <code>myModel1: {{myModel1 | json}}</code>
  <select ui-select2="select2Options" ng-model="myModel1" style="width:100%" ng-focus="focus()">
  </select>    
  <br>
  <br>    
  <code>myModel2: {{myModel2 | json}}</code>
  <select ui-select2="select2Options" ng-model="myModel2" style="width:100%" ng-focus="focus()" multiple>
  </select>
</body>

</html>

script.js

var myAppModule = angular.module('MyApp', ['ui.select2']);

myAppModule.controller('MyController', function($scope) {
    $scope.focus = function() {
      console.log('focus event');
    };

    $scope.select2Options = {
      allowClear: true,
      ajax: {
        url: "data.json",
        data: function (term, page) {
          return {}; 
        },
        processResults: function (data, page) { 
          return {results: data}
        }
      }
    }
});

How to make ng-model working?
How to make ng-focus working?
How to initialize select2 with defined value from server?

I know that ui-select2 is deprecated, but ui-select (native angular) does not fit.

P.S. I don't know why, but ng-model binding partially works if attribute "multiple" is defined - look the Plunker. But there is also bugs.
For example: if i click "clear", error generated
"Uncaught TypeError: Cannot read property 'id' of undefined"

0

There are 0 best solutions below