2013-08-26 54 views
2

我想創建一個自定義指令,其中包含一個文本框,當用戶單擊按鈕時顯示,展開和聚焦。而當用戶點擊遠離擴展文本框時,它應該最小化,消失並顯示原始按鈕。 這是我到目前爲止有: http://jsfiddle.net/Z6RzD/152/AngularJS自定義指令使用事件偵聽器

這裏是我有問題的部分:

if (htmlTxtBox.addEventListener !== undefined) { 
    console.log("first"); 

    htmlTxtBox.addEventListener('focus', setFocus(), false); 
    //this function is automatically called even when textBox is in focus    
    //htmlTxtBox.addEventListener('blur', setNoFocus(), false); 
    console.log("ifHasFocus: " + scope.showInput); 
} else if (htmlTxtBox.attachEvent != undefined) { 
    console.log("second"); 
    htmlTxtBox.attachEvent('onfocus', setFocus()); 
    htmlTxtBox.attachEvent('onblur', setNoFocus()); 
} else { 
    console.log("third"); 
    htmlTxtBox.onmouseover = setFocus(); 
    htmlTxtBox.onmouseout = setNoFocus(); 
} 

以及與事件偵聽器運行相應的功能:

function setFocus() { 
     scope.$apply('showInput = true'); 
     console.log("setFocus: " + scope.showInput);  
    } 
function setNoFocus(){ 
    scope.$apply('showInput = false'); 
    console.log("setNoFocus: " + scope.showInput); 
} 

我的問題是setFocus和setNoFocus函數無論如何運行。如何才能將這些功能構建到只有當文本框聚焦或模糊時才運行的位置? 我感謝任何幫助。謝謝!

回答

5

試試這個:

myApp.directive('replybox', function($timeout) { 
    var linkFn = function(scope, element, attrs) {  
     scope.showInput = false; 

     var button = element.find('button');   
     var input = element.find('input'); 

     button.bind("click", function() { 
      scope.showInput = true; 
      scope.$apply(); 

      input[0].focus(); 
      input.css({"width":"300px","transition":"1s"});    
     }); 

     input.bind('blur', function() { 
      scope.showInput = false;    
      $timeout(function() { scope.$apply(); }, 1000); 

      input.css({'width':'0px', 'transition':'1s'}); 
     }); 
    };  
... 

的jsfiddle here

+0

這就是機票!現在我試圖添加一個明確的文本圖標...我嘗試了以下,但無濟於事:http://jsfiddle.net/Z6RzD/158/ @Michael – sh3nan1gans

+1

任何使用'$ .bind'的具體原因,而不是'$ .on'? – pilau

+1

@pilau Angular的jqLit​​e在早期版本中只有'bind'。這在1.2RCx版本中已經改變了,因爲它們已經用'on'代替了'bind'。 –

相關問題