Last active
January 1, 2016 06:29
-
-
Save Deraen/8105660 to your computer and use it in GitHub Desktop.
AngularJS Selectize directive (tags)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
<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