Shreejibawa Shreejibawa - 4 months ago 42
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";

onChange:function(hsb, hex, rgb, iElement, bySetColor) {
if(!bySetColor) scope.ngModel = '#' + hex;


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) {
} else {