kaytrance
kaytrance

Reputation: 2757

Directive does not watches for value attribute changes

I have a color picker that gets opened when I click in input field and it writes back selected RGBA string to input's value attribute.

At first I thought that by adding ng-model="color" to the input tag will be sufficient for color variable to hold/bind rgba string of color that I choose, but it didn't worked. So I have tried to add custom directive to watch for input's value attribute changes by

// js
.directive('bindInput', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            scope.$watch( attrs.value , function (v) {
                console.log('value changed, new value is: ' + v);
            });
        }
    };
})

// html (jade)
input#text-highlight(ng-model="color",type="text",value="",bind-input)

If I open up console I could see that value changed gets outputted once on refresh. If I try to change color by opening up color picker I can see that the value appears in input, if I check value's attribute value with jquery (by $("text-highlight").val()) I can also see that the new color value is set to input's value attribute. But why I do no get any more value changed messages in the console?

Maybe I am doing something completely wrong here. In result what I want to have is just new color value being stored under $scope.color.

Upvotes: 0

Views: 66

Answers (1)

Elvin Valiev
Elvin Valiev

Reputation: 454

You need to bind property of the scope to your directive to watch it inside directive:

return {
    restrict: 'AE',
    scope: {
      myVar: '='
    },
   ...
}

  $scope.$watch('myVar', function(value) {
    // do something 
  });

And in your case you have to something like this :

scope: { value : '@'};

scope.$watch(attrs.value, function (newVal) {
  //do something with the new val
});

Upvotes: 0

Related Questions