Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selectize & AngularJS not playing along with Select box (Multiple options)

I've been trying to implement Selectize with AngularJS (1.2.4). I'm using this directive to interface with the plugin and everything is working smoothly until now. When using the ngModel from a normal select box It works fine, and returns the expected object but when I try to use it with the multiple attribute, it won't set the model.

I've inspected the DOM and appears the script removes unselected options from the hidden select and that might be messing with the angular binding.

I've created a Plunkr to demonstrate the behaviour.

http://plnkr.co/It6C2EPFHTMWOifoYEYA

Thanks

like image 439
Daniel T Avatar asked Oct 21 '22 14:10

Daniel T


1 Answers

As mentioned in the comments above, your directive must listen to changes in the selectize plugin and then inform angular of what happened via ng-model.

First, your directive needs to ask for an optional reference to the ngModel controller with the following:

require: '?ngModel'.

It is injected into your link function as an argument in the 4th position:

function(scope,element,attrs,ngModel){}

Then, you must listen for changes in selectize with $(element).selectize().on('change',callback)

and inform ngModel with ngModel.$setViewValue(value)

Here is a modified version of your directive. It should get you started.

angular.module('angular-selectize').directive('selectize', function($timeout) {
    return {
        // Restrict it to be an attribute in this case
        restrict: 'A',
        // optionally hook-in to ngModel's API 
        require: '?ngModel',
        // responsible for registering DOM listeners as well as updating the DOM
        link: function(scope, element, attrs, ngModel) {
            var $element;
            $timeout(function() {
                $element = $(element).selectize(scope.$eval(attrs.selectize));
                if(!ngModel){ return; }//below this we interact with ngModel's controller
                //update ngModel when selectize changes
                $(element).selectize().on('change',function(){
                    scope.$apply(function(){
                        var newValue = $(element).selectize().val();
                        console.log('change:',newValue);                    
                        ngModel.$setViewValue(newValue);
                    });
                });
            });
        }
    };
});

Also:

  • plunker
  • angular docs for ngModelController
like image 192
Jonathan Wilson Avatar answered Oct 23 '22 03:10

Jonathan Wilson