SturmUndDrang
SturmUndDrang

Reputation: 1956

Integrate Chosen into AngularJS

I'm trying to integrate Chosen (jquery plugin) with AngularJS, but I can't get it to populate any options in the select.

I started following this tutorial:

http://onehungrymind.com/angularjs-chosen-plugin-awesome/

and created this simple example (with help from 'Chosen Angular directive doesn't get updated'):

http://plnkr.co/edit/BzLAdotxKVI15t5phNAA?p=preview

module.directive('chosen', function(){

var directive = {};

    directive.restrict = 'A';


    directive.link = 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();
    };

    return directive;
});

which doesn't error but doesn't add anything to the list. If I remove the "chosen" attribute from the select, it works as expected so I know it's not a problem with the bindings.

I then tried using the angular-chosen wrapper:

https://github.com/localytics/angular-chosen (referenced in this question - Angular.js Chosen integration and (probably) AngularJS Chosen not working/updating)

and created this: http://plnkr.co/edit/NmQiDgU1xOK8l9MtTcjS?p=preview

Which has the same problem.

UPDATE In response to Jose M - I looked at ui-select but it requires a lot of (not-intuitive) markup instead of just an attribute, so I ruled it out.

UPDATE In response to **jd17* - * Working plunkr from the answer below: http://plnkr.co/edit/2v3BWVL0xFgQVce0MPXR?p=preview

Upvotes: 0

Views: 3359

Answers (1)

Jaydee88
Jaydee88

Reputation: 66

In your app.js, why did you redefine "chosen" directive since you are using the Angular Chosen plugin?
I modified your app.js in your second plnkr as follow and things works well.

var app = angular.module('myApp',['localytics.directives']); // inject the chosen

app.controller('TestController', ['$scope','$http',
function TestController($scope,$http){

  $scope.url = 'testValues.json';
  $scope.wordList = [];
  $scope.selectedWord = {};

  $scope.loadWords = function(){
    $http.get($scope.url).then(function(result){
      $scope.wordList = result.data;
    });
  };

  $scope.loadWords();
}
]);

Upvotes: 1

Related Questions