Prachi Pant
Prachi Pant

Reputation: 43

using jquery minicolors in angular.js

I am trying to incorporate jquery minicolors in an angular directive.The directive is binded to a textbox with ngModel. When I type the color code,the changed value is detected by the watch,but when I select it using colorpicker,the value is not reflected in the scope variable.Can any one tell me what am I doing wrong?

<input minicolors="colorPickerSettings" type="text" data-ng-model="category.ToBeConfirmedEventColor">


angular.
module('myApp', [])
.directive('minicolors', function () {
    return {
        require: 'ngModel',
        restrict: 'A',
        link: function (scope, element, attrs, ngModel) {            

            //gets the settings object
            var getSettings = function () {                    
                return angular.extend({}, scope.$eval(attrs.minicolors));
            };

            //init method
            var initMinicolors = function () {
              //  debugger
                if (!ngModel) {
                    return;
                }
                var settings = getSettings();

                //initialize the starting value, if there is one
                ngModel.$render = function () {
                    if (!scope.$$phase) {
                        //not currently in $digest or $apply
                        scope.$apply(function () {
                            var color = ngModel.$viewValue;
                            element.minicolors('value', color);
                        });
                    }
                };

                // If we don't destroy the old one it doesn't update properly when the config changes
                element.minicolors('destroy');

                // Create the new minicolors widget
                element.minicolors(settings);

                // Force a render to override whatever is in the input text box
                ngModel.$render();
            };

            // Watch model for changes  and then call init method again if any change occurs
            scope.$watch(getSettings, initMinicolors, true);
        }
    };
});

Upvotes: 1

Views: 1346

Answers (1)

Ilan Frumer
Ilan Frumer

Reputation: 32377

Whenever a change occurs inside the plugin, angular.js is unaware of it.
The input works because ngModel sets an event listener on the input element change event.
minicolors triggers a change event so you can register an event listener to update the model.

Take a look in the docs.

element.minicolors({
  value: color,
  change: function(hex, opacity) {
    // update the model
  }
});

Upvotes: 1

Related Questions