Shreejibawa Shreejibawa - 1 month ago 20
AngularJS Question

ngModel value is not updating in directive

I am trying to create a directive for color picker and value of ngModel value is not being updated. Any idea whats going wrong?

Here is my code:

.directive('colpkr', [function () {
return {
restrict: 'A',
scope: {
theme : "@theme",
ngModel : "="
},
link: function postLink(scope, iElement, iAttrs) {
theme = scope.theme || "light";

$(iElement).colpick({
layout:'hex',
submit:0,
colorScheme:theme,
onChange:function(hsb, hex, rgb, iElement, bySetColor) {
if(!bySetColor) scope.ngModel = '#' + hex;
}
});
}
};
}]);

Answer

You need to trigger a digest loop, which Angular uses to update the DOM, manually in your directive. scope.$apply() is an option, but you may encounter Error: $digest already in progress.

So you'd better use evalAsync or applyAsync to trigger a safe digest cycle,like

scope.$evalAsync(function () {
  scope.ngModel = '#' + hex;
});

Or you can merge these two options, do like some Angular built-in directives

if ($rootScope.$$phase) {
  scope.$evalAsync(callback);
} else {
  scope.$apply(callback);
}