I am encountering difficulties when utilizing the watch function within a directive in conjunction with a third-party plugin named selectize.
Despite researching extensively about $digest and $watch, I am still facing issues.
Although my example below is functioning, I am striving to avoid the $digest already in progress
errors.
There might be a more efficient approach to tackle this problem, but I am uncertain about it.
Check out the plunker link for reference: http://plnkr.co/edit/3JjTsEU2BlxPWHtw6HaW?p=preview
app.directive('selectize', function($parse) {
return {
restrict: 'A',
require: ['ngModel'],
scope: {
ngModel: '=',
options: '='
},
link: function(scope, el, attrs) {
var $select = el.selectize({
valueField: 'id',
labelField: 'name'
});
var selectize = $select[0].selectize;
// add options
angular.forEach('options', function(tag) {
selectize.addOption(tag);
});
scope.$watchCollection('options', function(newTags, oldTags) {
// why are these the same objects?
console.log('newTags', newTags);
console.log('oldTags', oldTags);
if (newTags !== oldTags) {
// clear options
selectize.clear();
selectize.clearOptions();
// add options
angular.forEach(newTags, function(tag) {
selectize.addOption(tag);
});
}
});
// if value changes without selecting an option,
// set the option to the new model val
scope.$watch('ngModel', function(val) {
console.log('val', val);
// selectize.setValue(val);
});
}
};
});