简体   繁体   中英

AngularJS with Bootstrap & Chosen: Select model not being updated with custom “chosen” directive

I'm using the Chosen plugin with AngularJS and Bootstrap. I'm also using a custom directive with code from the Chosen documentation for styling with Bootstrap:

app.directive("chosen", [function() {        
return {
    restrict: 'A',
    link: function(scope, element, attrs) {            
        var config = {
            '.chosen-select'           : {},
            '.chosen-select-deselect'  : {allow_single_deselect:true},
            '.chosen-select-no-single' : {disable_search_threshold:10},
            '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'},
            '.chosen-select-width'     : {width:"95%"}
        };

        for (var selector in config) {
            $(selector).chosen(config[selector]);
        }
    }
};
}]);

But when I apply this directive to the select box, it prevents the model from updating with the selected items. I've tried using chosen-bootstrap css and angular-chosen but cannot get it to work. Both left the select box unstyled (same as removing the custom directive) which leads me to believe it's an issue with Bootstrap.

Here's the issue recreated in Plunker: http://plnkr.co/edit/AE1jo9fiRN1pvU6dKFSI?p=preview

If you remove the "chosen-select" class on the select element it works fine but is not styled properly.

Any help would be much appreciated.

After a bit of googling seems like moving jQuery before Angular solved some other people's issues with Chosen + ng-model not updating. Your Plunker worked after I moved the script reference to jQuery before Angular.

  <head>
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
    <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" rel="stylesheet" />
    <link href="style.css" rel="stylesheet" />
    <link href="//cdnjs.cloudflare.com/ajax/libs/chosen/1.0/chosen.min.css" rel="stylesheet" />
    <script data-require="jquery@2.1.4" data-semver="2.1.4" src="https://code.jquery.com/jquery-2.1.4.js"></script>
    <script src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8" data-require="angular.js@1.4.8"></script>
    <script src="https://code.angularjs.org/1.4.8/angular-route.js" data-semver="1.4.8" data-require="angular-route@1.4.8"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.0/chosen.jquery.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.0/chosen.proto.min.js"></script>
    <script src="script.js"></script>
  </head>

See working Plunker here: http://plnkr.co/edit/ISqrJiiYB3a0ATkR1Dei?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM