AngularJS select2

109 Views Asked by At

Good day. I am trying to create a select2 in angularJS. I have search and found this code but upon using it and put it in my code I got this error element.select2 is not a function. I've used it(select2) before but It was in jquery not angularJS. But that was way back year ago. I'm a newbie to angularJS. Is something that I need to modify first to make it work?.

var app = angular.module('TestApp');

app.controller('TestCtrl', function ($scope) {
        $scope.optionList = {
            'key1': 'Option 1',
            'key2': 'Option 2',
            'key3': 'Option 3',
            'key4': 'Option 4'
        };

        $scope.selectedOption = 'key3';
        $scope.changeModelOutside = function () {
            $scope.selectedOption = 'key4';

        };
   
});


app.directive('wbSelect2', function () {
    return {
        restrict: 'A',
        scope: {
            'selectWidth': '@',
            'ngModel': '='
        },
        link: function (scope, element, attrs) {
            //Setting default values for attribute params
            scope.selectWidth = scope.selectWidth || 200;
            element.select2({
                width: scope.selectWidth,
            });

            scope.$watch('ngModel', function (newVal, oldVal) {
                window.setTimeout(function () {
                    element.select2("val", newVal);
                });
            });
        }
    };
});
<!DOCTYPE html>
<html ng-app="TestApp" ng-controller="TestCtrl">
<head>

    <link href="../contents/bootstrap.css" rel="stylesheet" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" />

    <script src="../../scripts/angular.min.js"></script>
    <script src="../../scripts/angular-route.min.js"></script>



    <!-- Sweet Alert Scripts-->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>

    <meta charset="utf-8" />
    <base href="/" />
    <title></title>
</head>
<body>
    <select ng-model="selectedOption" wb-select2 select-width="300px">
        <option ng-repeat="(k, v) in optionList" value="{{k}}">{{v}}</option>

    </select>
    <button ng-click="changeModelOutside()">Click me</button>
</body>
</html>

0

There are 0 best solutions below