Angular.js Chosen integration

thegrunt picture thegrunt · Feb 25, 2013 · Viewed 15.1k times · Source

my select inside my angular view where i want to add chosen functionality:

<select ng-options="value for value in deutscheBankEvent.dates" ng-init="" ng-model="chosenA" class="chzn-select">
 <option style="display:none" value="">Wählen Sie ein Datum</option>
 </select><br/>

my controller: when i inject here the .chosen function, it clears the options.

function Ctrl($scope,$http) {

  $scope.text = '';
  $scope.user = {name: '', last: '', location: ''};
  $scope.value = 0;
  $scope.sendForm = function (){
       $http.post('/Submit/To/Url', $scope.data).success(function(data) {
           alert('done!');
       });
    };
}

my footer:

<g:javascript>
 $(".chzn-select").chosen(); $(".chzn-select-deselect").chosen({allow_single_deselect:true});
            jQuery(".adressen1_chzn-select").chosen();jQuery(".adressen0_chzn-select").chosen();
        });
</g:javascript>

i have no idea, how to get the chosen working. inside controller it clears options and does not apply, the rest does not make any difference. any ideas appreciated

Answer

Kulbi picture Kulbi · Nov 28, 2013

Your solution won't work because jQuery code would fire before the element is actually created in the DOM. You should solve this problem using a directive on the form element.

Element needs to be created dynamically and therefore you are in fact operating on the DOM element - perfect fit for Angular's directives. No use of jQuery is necessary and try to avoid it while working with Angular. Note that jQuery is still required due to Chosen dependencies.

I solve the problem using this set:

  1. angular-chosen directive https://github.com/localytics/angular-chosen
  2. [OPTIONAL] Bootstrap3 styling https://github.com/alxlit/bootstrap-chosen

I suggest you to try writing the directive yourself. It's a nice practice. You can try with this: http://www.youtube.com/watch?v=8ozyXwLzFYs

Good luck!