2013-07-03 25 views
2

作爲練習,我使用RGB和十六進制爲顏色值創建輸入。將相互依賴但不同的數據格式綁定到角度輸入

HTML:

<form ng-controller="myCtrl"> 
    R:<input ng-model="rChannel" type="number" min="0" max="255" required></input> 
    G:<input ng-model="gChannel" type="number" min="0" max="255" required></input> 
    B:<input ng-model="bChannel" type="number" min="0" max="255" required></input> 

    hex: #<input ng-model="hexColor" type="text" required></input> 
</form> 

JS:

function myCtrl($scope) { 
    $scope.$watch('[rChannel, gChannel, bChannel]', 
       function() { 
       $scope.hexColor = rgbToHex($scope.rChannel, $scope.gChannel, $scope.bChannel) 
       }, 
       true); 

    $scope.$watch('hexColor', 
       function() { 
       var rgbArr = hexToRgbArray($scope.hexColor); 
       $scope.rChannel = rgbArr[0]; 
       $scope.gChannel = rgbArr[1]; 
       $scope.bChannel = rgbArr[2]; 
       }); 
} 

http://jsfiddle.net/F545z/

它的工作原理...一個大嗝。當任何一個輸入值變爲無效時(一個空字符串,或十六進制小於六個字符),所有輸入消失!這具有刪除用戶已經輸入的值的效果。例如。當用戶輸入一個有效的6個字符的十六進制值,然後按下刪除鍵來糾正十六進制的最後一個字符時,整個十六進制值就會消失,並且需要完全重新輸入。如果你在控制檯中觀看,你可以看到發生了什麼。我認爲當十六進制無效時rgb輸入消失的正確行爲,但顯然阻礙了用戶在輸入過程中抹去他/她的值。

這顯然是因爲「雙重綁定」 - rgb和十六進制值正在看自己的模型,但也是彼此。這裏存在一些嚴重的無限循環潛力,並且它可能只能工作,因爲可以防止死循環的死循環,因爲the angular docs say the loop only runs 10x

我很確定我是以這種錯誤的方式開始的。我應該嘗試爲十六進制輸入編寫單獨的指令嗎?如果是這樣,我應該如何將它們連接起來? $看這種用途的合法嗎?一個工作小提琴是最有幫助的。

回答

5

$ watch適用於單向依賴。您希望根據用戶輸入的內容來獲得觸發器的依賴關係。對於這一點,使用的輸入NG-變化:

http://jsfiddle.net/F545z/1/

<div ng-app> 
    <form ng-controller="myCtrl" novalidate> 
     R:<input ng-model="redChannel" ng-change="updateHex()" type="number" min="0" max="255" required></input> 
     G:<input ng-model="greenChannel" ng-change="updateHex()" type="number" min="0" max="255" required></input> 
     B:<input ng-model="blueChannel" ng-change="updateHex()" type="number" min="0" max="255" required></input> 
     <br><br> 
     hex: #<input ng-model="hexColor" ng-change="updateChannels()" type="text" required></input> 
    </form> 
</div> 
+0

優秀。謝謝。 – Ben