I am creating an angular directive for the ChosenJS plugin based on this tutorial here: https://www.youtube.com/watch?v=8ozyXwLzFYs
What I want to do is have the model update when a value is selected.
function Foo($scope) {
$scope.legalEntitiesList = [
{ name: 'Foo' },
{ name: 'Bar' }
];
$scope.legalEntity = { name: 'Foo' };
}
myApp.directive('chosen', ['$timeout', function($timeout) {
var linker = function(scope, element, attrs, ngModel) {
if (!ngModel) return;
element.addClass('chzn-select');
$(element).chosen()
.change(function(e) {
console.log(ngModel.$viewValue);
});
scope.$watch(attrs.chosen, function() {
$(element).trigger('liszt:updated');
});
}
return {
restrict: 'A',
scope: true,
require: '?ngModel',
link: linker
}
}]);
Here is a fiddle: http://jsfiddle.net/dkrotts/MQzXq/7/. If you select a different option, the model value is not updated.
If you modify the select to bind to legalEntity.name
instead of just legalEntity
your fiddle works.
<select id="legalEntityInput" chosen="legalEntitiesList" ng-model="legalEntity.name" ng-options="legalEntity.name for legalEntity in legalEntitiesList" data-placeholder="Select..."><option></option></select>
See this updated fiddle for an example.
I wanted to add this as a comment, but I'm lacking reputation points. However, please note that newer versions of Chosen use the event chosen:updated
instead of liszt:updated
-- Thanks for the video, Dustin!