Shreejibawa
Shreejibawa

Reputation: 1868

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;
                        }
                    });
                }
            };
        }]);

Upvotes: 3

Views: 5059

Answers (4)

Rahul juneja - DevOps
Rahul juneja - DevOps

Reputation: 790

Worked like a charm

  scope.$evalAsync(function() {

       var ngModel = $parse(attrs.ngModel),

       newValue = 'Its working';

       ngModel.assign(scope, newValue);
  });

Upvotes: 0

Aakash
Aakash

Reputation: 23727

Inject $parse service in your directive. Then you can $parse(attrs.ngModel) to which you can assign the new value.

// inject $parse service in your directive
// Your link function
function link(scope, el, attrs) {
    el.on('change', function() {
        scope.$evalAsync(function() {
            var
                // parse the ngModel
                ngModel = $parse(attrs.ngModel),
                // get the new value
                newValue = el.val();
            // 
            ngModel.assign(scope, newValue);
        })
    })
}

Good Luck.

Upvotes: 0

Rebornix
Rebornix

Reputation: 5270

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);
}

Upvotes: 3

user3167794
user3167794

Reputation:

You might want to refresh scope.

Use

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

Upvotes: 2

Related Questions