Chosen Angular directive doesn't get updated

前端 未结 2 2068
既然无缘
既然无缘 2021-01-02 12:21

I\'ve followed this great tutorial (link) for Chosen and Angular (code is pretty much same)

Here is my directive:

app.angularModule.directive(\'chose         


        
相关标签:
2条回答
  • 2021-01-02 13:18

    I've solved it, the solution is pretty easy and straightforward actually (when you get how Angular directives work). Here is whole code for directive:

    app.angularModule.directive('chosen', function() {
        var linker = function (scope, element, attrs) {
            var list = attrs['chosen'];
    
            scope.$watch(list, function () {
                element.trigger('chosen:updated');
            });
    
            scope.$watch(attrs['ngModel'], function() {
                element.trigger('chosen:updated');
            });
    
            element.chosen({ width: '350px'});
        };
    
        return {
            restrict: 'A',
            link: linker
        };
    });
    
    0 讨论(0)
  • 2021-01-02 13:23

    More expanded version of comment to previous solution. Same as author, in HTML markup I provide source collection like chosen="vm.myCollection", actually parsing ng-options or ng-repeat property with regexp is better, maybe later. In contrast with OP, I use $watchCollection for an array, and call unwatches when scope is about to destroy.

    (function () {
        'use strict';
        angular.module('common.directives').directive('chosen', enterPressDirective);
    
        function enterPressDirective() {
            return {
                restrict: 'A',
                link: function (scope, elm, attrs) {
                    var unwatchModel = scope.$watch(attrs.ngModel, function () {
                        elm.trigger('chosen:updated');
                    });
    
                    var unwatchSource = scope.$watchCollection(attrs.chosen, function () {
                        elm.trigger('chosen:updated');
                    });
    
                    elm.chosen();
    
                    scope.$on('$destroy', function () {
                        unwatchModel();
                        unwatchSource();
                    });
                }
            };
        }
    }());
    
    0 讨论(0)
提交回复
热议问题