Angularjs Custom select2 directive

后端 未结 5 1882
温柔的废话
温柔的废话 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:22

    It might be simpler than you expected!

    Please have a look at this Plunker

    Basically, all plugins, Angularjs $watch need to be based on something. I'm not 100% sure for jQuery-select2; but I think that's just the control's normal DOM events. (And in the case of Angular $watch, it is a "dirty checking loop")

    My idea is that let's trust jquery-Select2 and AngularJS for handling those change events.

    We just need to watch for change in Angular's ways and update the select in Select2's ways

    var refreshSelect = function() {
        if (!element.select2Initialized) return;
        $timeout(function() {
            element.trigger('change');
        });
    };
    
    //...
    
    scope.$watch(attrs.ngModel, refreshSelect);
    

    Notice: I have added in 2 new watch which I think you would like to have!

提交回复
热议问题