0

I have a controller and a directive that I want to use two way data binding on an object. The purpose of the directive is simply to update the value. Currently I am not getting the data binding to work properly because in the onchange event when I update the bound variable the background color of the div does not change. Also when I open the color wheel the value of the wheel is not the scope.activeColor.

My HTML looks like this, it has the directive and a div with ng-style.

 <li ng-repeat="(key, color) in colors" ng-style="{'background': 'rgb(' + color.r + ',' + color.g + ','+ color.b}" ng-click="editColour(color)">
 <div ng-style="{'background': 'rgb(' + activeColor.r + ',' + activeColor.g + ','+ activeColor.b}"></div>

 <input type="text" colorwheel value="currentColor">

In my controller I define the object:

$scope.editColour = function(colour) {
  $scope.activeColor = colour;
};

My directive is the following:

.directive('colorwheel', function() {
      return {
          restrict: 'A',
          link: function(scope, element) {
            var currentColor = 'rgb(' + scope.activeColor.r + ',' + scope.activeColor.g + ',' + scope.activeColor.b + ')';
            scope.currentValue = {color: currentColor};
            element.minicolors({
              control: 'wheel',
              format: 'rgb',
              inline: true,
              opacity: false,
              change: function(value, opacity) {
                var rgb = element.minicolors('rgbObject');
                scope.activeColor.r = rgb.r;
                scope.activeColor.g = rgb.g;
                scope.activeColor.b = rgb.b;
                console.log(rgb);
              }
            });
          }
      };
  });
tester123
  • 1,033
  • 2
  • 12
  • 17
  • The directive doesn't define any data binding. See http://stackoverflow.com/questions/14050195/angularjs-what-is-the-difference-between-and-in-directive-scope – Tristan Nov 30 '15 at 18:36
  • you probably need to watch scope.activeColor inside the directive, can help you better if you post a fiddle or a snippet here – gaurav5430 Nov 30 '15 at 18:47

1 Answers1

0

You need to watch the activecolor variable in the directive so that directive understands that the variable has been changed

An Example can be

$scope.$watch('activeColor', function (newValue, oldValue) {
                     if (newValue) {
                       //do something with new value
                     }
                 });
Rama Krshna Ila
  • 486
  • 3
  • 11