How to use jQuery Select2 with AngularJS

Viewed 25609

I am trying to use jQuery (2.2.1) Select2 (3.5.2) with Angularjs (1.5) but am having a difficult time grabbing the data from the select box. I have tried ui-select and I could retrieve data... but would often crash the browser when searching, was horribly slow and overall unstable (5000-10000 items). jQuery Select2 is fast and responsive, even with the large number of entries, but I cant seem to get the object when I select an option.

<head>
    <script src="~/Scripts/angular.min.js"></script>
    <script src="~/Scripts/CustomScripts/app.js"></script>
    <script src="~/Scripts/jquery-2.2.1.js"></script>
    <script src="~/Scripts/select2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $(".sel").select2();
        });
    </script>
<head>
<body ng-app="app" ng-controller="MainCtrl">
    <select class="sel" data-ng-model="country.selected" ng-options="country.Name for country in countries | orderBy: 'Name'">
<body>

app.js

var app = angular.module('app', []);

app.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) {

    $scope.country = {};

    $scope.countries = [{
        name: 'Australia',
    }, {
        name: 'United States'
    }, {
        name: 'United Kingdom'
    }];

}]);

Is there a way to get these two working nicely?

4 Answers

You can use this plugin ,
ngx-select2

Add jQuery and Select2 lib

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

If you want to add javascript and css libraries , you msust added from angular.json example :

 "styles": [
      "node_modules/bootstrap/dist/css/bootstrap.css",
      "src/styles.css",
      "src/assets/css/select2.min.css"
    ],
    "scripts": [
      "node_modules/bootstrap/dist/js/bootstrap.js",
      "node_modules/jquery/dist/jquery.js",
      "src/assets/js/select2.min.js"
    ]

Install ngx-select2

npm i ngx-select2

Use select2 component

import { LSelect2Module } from 'ngx-select2';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    LSelect2Module
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

in html

<l-select2 [(ngModel)]="selected" [data]="data" [options]="options" [disabled]="false" (valueChange)="valueChange($event)"></l-select2>

Options

  • data: select2 init data for select
  • options: select2 options
  • disabled: disable select2 component
  • valueChange: output. Fire on value change, same as ngModelChange
Related