Skip to content

Instantly share code, notes, and snippets.

@Deraen
Last active January 1, 2016 06:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Deraen/8105660 to your computer and use it in GitHub Desktop.
Save Deraen/8105660 to your computer and use it in GitHub Desktop.
AngularJS Selectize directive (tags)
/*
<input tagcomplete ng-model="skill.tags" options="tags" data-placeholder="Valitse avainsanoja" class="form-control">
Where skill.tags = [{_id: ..., name: 'Something'}, {_id: ..., name: 'Another'}];
...or maybe it is ['Something', 'Another'];
*/
angular.module('frontendApp')
.directive('tagcomplete', function($parse) {
return {
restrict: 'A',
// templateUrl: 'views/common/autocomplete.html',
// replace: true,
require: ['?ngModel'],
scope: {
options: '=',
placeholder: '@', // Use as value
},
link: function(scope, el, attrs, ctrls) {
console.log(ctrls);
var modelCtrl = ctrls[0];
var $select = el.selectize({
create: function(input, cb) {
cb({name: input});
},
valueField: 'name',
labelField: 'name',
searchField: 'name',
plugins: ['remove_button'],
hideSelected: true,
onChange: function(val) {
scope.$apply(function() {
var selected = _.map(val.split(','), function(tag) {
return {_id: 1, name: tag};
});
modelCtrl.$setViewValue(selected);
});
},
});
var selectize = $select[0].selectize;
scope.$watchCollection('options', function(newTags, oldTags) {
_.each(newTags, function(tag) {
selectize.addOption(tag);
});
});
scope.$watch(function() { return modelCtrl.$viewValue }, function(vals) {
_.each(vals, function(tag) {
console.log('render', vals.length);
selectize.addItem(tag.name);
});
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment