Angularjs Custom select2 directive

后端 未结 5 1884
温柔的废话
温柔的废话 2021-02-04 04:36

I have created simple custom AngularJs directive for this awesome jquery plugin jQuery-Select2 as follows:

Directive

app.directive(\"sel         


        
5条回答
  •  渐次进展
    2021-02-04 05:39

    I'm not that familiar with select2 (so the actual API for getting and setting the displayed value in the control may be incorrect), but I suggest this as an alternative:

    app.directive("select2",function($timeout){
        return {
            restrict: 'AC',
            require: 'ngModel',
            link: function(scope, element, attrs, model) {
    
                $timeout(function() {
                    element.select2();
                });
    
                model.$render = function() {
                    element.select2("val",model.$viewValue);
                }
                element.on('change', function() {
                    scope.$apply(function() {
                        model.$setViewValue(element.select2("val"));
                    });
                })
            }
        };
    });
    

    The first $timeout is necessary because you are using ng-options, so the options won't be in the DOM until the next digest cycle. The problem with this is that new options won't be added to the control if the countries model is later changed by your application.

提交回复
热议问题