Question

I'm having trouble using watch inside of a directive along with a 3rd party plugin called selectize.

I've read a lot about $digest/$watch, but am still having problems.

My example below "works", but i'm trying to prevent the $digest already in progress errors.

There may be a better way to approach this, im just not sure how too.

plunker: 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);
    });
  }
};
});
Was it helpful?

Solution

Try wrapping the calls to the 3rd party inside a $timeout like this:

$timeout(function() {
    // clear options
    selectize.clear();
    selectize.clearOptions();

    // add options
    angular.forEach(newTags, function(tag) {
      selectize.addOption(tag);
    });

}, 0);

And don't forget to inject $timeout.

With a timeout of zero (leaving out the value defaults to 0 as well…), I believe this is guaranteed to run during the next digest loop, thus preventing the already in progress errors. Someone please chime in if that is correct, but I have used this trick to solve the digest errors when calling some third party (tinyMce) javascript functions.

See betaorbust's explanation in this SO post: AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

OTHER TIPS

I recently created a directive for Selectize that supports 2-way binding of the model and the options. I also had to use $timeout.

https://github.com/machineboy2045/angular-selectize

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

Here's the essential parts of the directive. I stripped out some additional functionality that's in the full version.

app.directive('selectize', function($timeout) {
  return {
    restrict: 'A',
    require: '^ngModel',
    link: function(scope, element, attrs, ngModel) {

      var config = scope.$eval(attrs.selectize);
      config.options = scope.$eval(attrs.options) || [];
      element.selectize(config);
      var selectize = element[0].selectize;

      selectize.on('option_add', refreshAngularOptions);
      scope.$watch(function(){ return ngModel.$modelValue}, refreshSelectize, true)

      function refreshAngularOptions(value, data) {
        config.options = selectize.options;
      }

      function createOption(opt){
        var newOpt = {};
        newOpt[selectize.settings.valueField] = opt;
        newOpt[selectize.settings.labelField] = opt;
        selectize.addOption(newOpt);
      }

      function refreshSelectize(value){
        $timeout(function(){
          if(angular.isArray(value))
            angular.forEach(value, createOption);
          else
            createOption(value);

          selectize.refreshOptions(false);
          selectize.setValue(value); 
        })
      }
    }
  };
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top