2014-01-23 59 views
1

我想將jquery minicolors合併到角度指令中。該指令綁定到ngModel的文本框。當我輸入顏色代碼時,手錶檢測到更改的值,但是當我使用colorpicker選擇它時,值不會反映在範圍變量中。可以有人告訴我我做錯了什麼?在angular.js中使用jquery minicolors

<input minicolors="colorPickerSettings" type="text" data-ng-model="category.ToBeConfirmedEventColor"> 


angular. 
module('myApp', []) 
.directive('minicolors', function() { 
    return { 
     require: 'ngModel', 
     restrict: 'A', 
     link: function (scope, element, attrs, ngModel) {    

      //gets the settings object 
      var getSettings = function() {      
       return angular.extend({}, scope.$eval(attrs.minicolors)); 
      }; 

      //init method 
      var initMinicolors = function() { 
       // debugger 
       if (!ngModel) { 
        return; 
       } 
       var settings = getSettings(); 

       //initialize the starting value, if there is one 
       ngModel.$render = function() { 
        if (!scope.$$phase) { 
         //not currently in $digest or $apply 
         scope.$apply(function() { 
          var color = ngModel.$viewValue; 
          element.minicolors('value', color); 
         }); 
        } 
       }; 

       // If we don't destroy the old one it doesn't update properly when the config changes 
       element.minicolors('destroy'); 

       // Create the new minicolors widget 
       element.minicolors(settings); 

       // Force a render to override whatever is in the input text box 
       ngModel.$render(); 
      }; 

      // Watch model for changes and then call init method again if any change occurs 
      scope.$watch(getSettings, initMinicolors, true); 
     } 
    }; 
}); 
+0

您能否請創建一個工作的重擊者?我試過沒有成功:http://plnkr.co/edit/v4mZvUTkHG7wnHUSmNSu?p=preview –

+0

http://plnkr.co/edit/tz0OuqD8l8380tkdH7pf?p=preview –

+0

這已完成。你應該檢查出http://kaihenzler.github.io/angular-minicolors/ – Alp

回答

1

無論何時在插件內部發生變化,angular.js都不知道它。
輸入的工作原理是因爲ngModel在輸入元素更改事件上設置了事件偵聽器。
minicolors觸發更改事件,以便您可以註冊事件偵聽器來更新模型。

看一看in the docs

element.minicolors({ 
    value: color, 
    change: function(hex, opacity) { 
    // update the model 
    } 
}); 
+1

好的,但我無法達到ngModel。$ render()函數,而我正在選擇顏色。請告訴我該放置此更改事件的位置? –